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 |
|---|---|---|---|---|
02.代码实现-06Tensorflow-01Cifar10-01基本网络.py | 100
线性全连接层:神经元个数10
softmax层
'''
import tensorflow as tf
import os
import cifar_input,cifar_toTFRecords
import numpy as np
import csv
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
learning_rate_init = 0.001
training_epochs = 1
batch_size = 100
display_step = 10
dataset_dir = '../Total_Data/TempData/'
num_examples_per_epoc... | l1_out = Pool2d(conv1_out, pool=tf.nn.max_pool, k=3, stride=2, padding='SAME')
with tf.name_scope('Conv2d_2'): # 卷积层2
weights = WeightsVariable(shape=[5, 5, conv1_kernel_num, conv2_kernel_num], name_str='weights', stddev=5e-2)
biases = BiasesVariable(shape=[conv2_kernel_num], name_str='biases', ini... | poo | identifier_name |
enel645_group11_final_project.py | _classes):
self.input_paths = in_paths
self.target_paths = out_paths
self.img_size = img_size
self.n_channels = n_channels
self.n_classes = n_classes
def | (self):
return len(self.target_paths)
def __getitem__(self, idx):
'''Returns tuple (input, target) correspond to batch #idx.'''
i = idx
path = self.input_paths[i]
target_path = self.target_paths[i]
img = tf.keras.preprocessing.image.load_img(path, color_mode='rgb', ... | __len__ | identifier_name |
enel645_group11_final_project.py | _classes):
self.input_paths = in_paths
self.target_paths = out_paths
self.img_size = img_size
self.n_channels = n_channels
self.n_classes = n_classes
def __len__(self):
return len(self.target_paths)
def __getitem__(self, idx):
'''Returns tuple (input, ta... | train_gen = DataSequence(train_input_paths, train_target_paths)
val_gen = DataSequence(val_input_paths, val_target_paths)
test_gen = DataSequence(test_input_paths, test_target_paths)
print('simulation data train_samples', train_samples)
print('simulation data val_samples', val_samples)
print('simulation data test_samp... | val_samples:train_samples + val_samples + test_samples]
| random_line_split |
enel645_group11_final_project.py | _classes):
self.input_paths = in_paths
self.target_paths = out_paths
self.img_size = img_size
self.n_channels = n_channels
self.n_classes = n_classes
def __len__(self):
return len(self.target_paths)
def __getitem__(self, idx):
'''Returns tuple (input, ta... |
def jaccard_coef(y_true, y_pred, smooth=1):
intersection = tf.keras.backend.sum(
tf.keras.backend.abs(y_true * y_pred), axis=-1)
sum_ = tf.keras.backend.sum(tf.keras.backend.abs(
y_true) + tf.keras.backend.abs(y_pred), axis=-1)
jac = (intersection + smooth) / (sum_ - intersection + smooth... | inputs = tf.keras.backend.flatten(inputs)
targets = tf.keras.backend.flatten(targets)
BCE = tf.keras.backend.binary_crossentropy(targets, inputs)
BCE_EXP = tf.keras.backend.exp(-BCE)
focal_loss = tf.keras.backend.mean(
alpha * tf.keras.backend.pow((1-BCE_EXP), gamma) * BCE)
return focal_loss | identifier_body |
enel645_group11_final_project.py |
mapping = {
(31, 120, 180): 0,
(106, 176, 25): 1,
(156, 62, 235): 2,
(255, 255, 255): 3,
(69, 144, 232): 4,
(227, 26, 28): 5,
}
class DataSequence(tf.keras.utils.Sequence):
'''Helper to iterate over the data as Numpy arrays.'''
def __init__(self, in_paths, out_paths, img_size=IMG_SI... | print(input_path, '|', target_path) | conditional_block | |
supplyGoodsList.js | 15,
paddingBottom:15,
flexDirection: 'row',
alignItems:'center',
marginTop:10,
},
item: {
height: 45,
backgroundColor: 'fff',
paddingLeft: 15,
paddingRight: 15,
alignItems: 'center',
flexDirection: 'row',
},
border_bottom: {... | rowData 商品信息
* @private
*/
_btn | conditional_block | |
supplyGoodsList.js | .route.data.supplierId
}
this._ds = new ListView.DataSource({
sectionHeaderHasChanged: (r1, r2) => r1 !== r2,
rowHasChanged: (r1, r2) => r1 !== r2
});
this._renderRow=this._renderRow.bind(this);
this._itemClick=this._itemClick.bind(this);
this._btn... | lignItems:'center'}}>
<SText fontSize="headline" color="fff" styl | identifier_body | |
supplyGoodsList.js | : 15,
paddingTop:15,
paddingBottom:15,
flexDirection: 'row',
alignItems:'center',
marginTop:10,
},
item: {
height: 45,
backgroundColor: 'fff',
paddingLeft: 15,
paddingRight: 15,
alignItems: 'center',
flexDirection: 'row',
... | name}</SText>
<SText fontSize="caption" color="orange" style={{marginLeft:3}}>{rowData.value}</SText>
</View>
)
}
/**
* 商品属性 展开隐藏事件
* @param rowData
* @private
*/
_itemSpreadClick(rowData) {
if (rowData.spread) {
rowData.spread=fa... | lor="999">{rowData. | identifier_name |
supplyGoodsList.js | paddingRight: 15,
paddingTop:15,
paddingBottom:15,
flexDirection: 'row',
alignItems:'center',
marginTop:10,
},
item: {
height: 45,
backgroundColor: 'fff',
paddingLeft: 15,
paddingRight: 15,
alignItems: 'center',
flexDirecti... | </TouchableOpacity>
{
// <TouchableOpacity onPress={()=>this._btnDetailsClick(rowData)} style={[s.itemButton,{marginLeft:15}]}>
// <SText fontSize="body" color="666" style={{color:"#2296f3"}} >详情</SText>
... | <SText fontSize="caption" color="333" style={s.text_right} >{rowData.currentPriceDes}</SText>
</View>
<View style={{flexDirection:'row',justifyContent:'flex-end',height:60,backgroundColor:'#fafafa',alignItems:'center',paddingRight:15}}>
<TouchableO... | random_line_split |
api_op_RecognizeUtterance.go | .
InputStream io.Reader
// Request-specific information passed between the client application and Amazon
// Lex V2 The namespace x-amz-lex: is reserved for special attributes. Don't
// create any request attributes for prefix x-amz-lex: . The requestAttributes
// field must be compressed using gzip and then base6... | {
return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil")
} | conditional_block | |
api_op_RecognizeUtterance.go | ) | (ctx context.Context, params *RecognizeUtteranceInput, optFns ...func(*Options)) (*RecognizeUtteranceOutput, error) {
if params == nil {
params = &RecognizeUtteranceInput{}
}
result, metadata, err := c.invokeOperation(ctx, "RecognizeUtterance", params, optFns, c.addOperationRecognizeUtteranceMiddlewares)
if err ... | RecognizeUtterance | identifier_name |
api_op_RecognizeUtterance.go | // - Failed message - The failed message is returned if the Lambda function
// throws an exception or if the Lambda function returns a failed intent state
// without a message.
// - Timeout message - If you don't configure a timeout message and a timeout,
// and the Lambda function doesn't return within... | random_line_split | ||
api_op_RecognizeUtterance.go | // create any request attributes for prefix x-amz-lex: . The requestAttributes
// field must be compressed using gzip and then base64 encoded before sending to
// Amazon Lex V2.
RequestAttributes *string
// The message that Amazon Lex V2 returns in the response can be either text or
// speech based on the respon... | {
if awsmiddleware.GetRequiresLegacyEndpoints(ctx) {
return next.HandleSerialize(ctx, in)
}
req, ok := in.Request.(*smithyhttp.Request)
if !ok {
return out, metadata, fmt.Errorf("unknown transport type %T", in.Request)
}
if m.EndpointResolver == nil {
return out, metadata, fmt.Errorf("expected endpoint re... | identifier_body | |
admin.py | import force_str
from django.utils.safestring import mark_safe
from django.utils.translation import ngettext
from concurrency import core, forms
from concurrency.api import get_revision_of_object
from concurrency.compat import concurrency_param_name
from concurrency.config import CONCURRENCY_LIST_EDITABLE_POLICY_ABOR... |
else:
return []
def save_model(self, request, obj, form, change):
try:
if change:
version = request.POST.get(f'{concurrency_param_name}_{obj.pk}', None)
if version:
core._set_version(obj, version)
super().save_... | return request._concurrency_list_editable_errors | conditional_block |
admin.py | force_str
from django.utils.safestring import mark_safe
from django.utils.translation import ngettext
from concurrency import core, forms
from concurrency.api import get_revision_of_object
from concurrency.compat import concurrency_param_name
from concurrency.config import CONCURRENCY_LIST_EDITABLE_POLICY_ABORT_ALL, ... |
def _get_concurrency_fields(self):
v = []
for pk, version in self._versions:
v.append(f'<input type="hidden" name="{concurrency_param_name}_{pk}" value="{version}">')
return mark_safe("".join(v))
def render(self, template_name=None, context=None, renderer=None):
ou... | self._versions = kwargs.pop('versions', [])
super().__init__(*args, **kwargs) | identifier_body |
admin.py | import force_str
from django.utils.safestring import mark_safe
from django.utils.translation import ngettext
from concurrency import core, forms
from concurrency.api import get_revision_of_object
from concurrency.compat import concurrency_param_name
from concurrency.config import CONCURRENCY_LIST_EDITABLE_POLICY_ABOR... | if hasattr(request, '_concurrency_list_editable_errors'):
return request._concurrency_list_editable_errors
else:
return []
def save_model(self, request, obj, form, change):
try:
if change:
version = request.POST.get(f'{concurrency_param_na... |
def _get_conflicts(self, request): | random_line_split |
admin.py | force_str
from django.utils.safestring import mark_safe
from django.utils.translation import ngettext
from concurrency import core, forms
from concurrency.api import get_revision_of_object
from concurrency.compat import concurrency_param_name
from concurrency.config import CONCURRENCY_LIST_EDITABLE_POLICY_ABORT_ALL, ... | (self, request, queryset): # noqa
"""
Handle an admin action. This is called if a request is POSTed to the
changelist; it returns an HttpResponse if the action was handled, and
None otherwise.
"""
# There can be multiple action forms on the page (at the top
# and... | response_action | identifier_name |
soldev.datatable.js | type":"checkbox","class":"select_filter_"+filter.id,"value":filter.id});
$input_wrapper = $label.append($input).append(filter.label);
$wrapper = $checkbox_wrapper.append($input_wrapper);
$('.add_filter_content > form').append($wrapper);
});
... | //add buttons | random_line_split | |
soldev.datatable.js | ('type') == 'range' ){
value = {
min: $('.dt-filter-range',filterElm).slider("values",0),
max: $('.dt-filter-range',filterElm).slider("values",1),
}
}
else if (filterElm.data('type') == 'daterange' ){
value = {
... |
else if(properties.select == 'multi'){
selectProperties.style ='multi';
}
}else selectProperties.style = 'os';
selectProperties.info = false;
dtTblProperties.select = selectProperties;
if(typeof(properties.destroy)!=='undefinded' && properties.destroy != null && properties.destroy.l... | {
selectProperties.style = 'single';
} | conditional_block |
main.js | ">')
.text(data.message);
var $messageDiv = $('<li class="message"/>')
.data('username', data.username)
//.addClass(typingClass)
.append($usernameDiv, $messageBodyDiv);
addMessageElement($messageDiv, options);
}
// Adds the visual chat message to the message list
const addNotifi... | {
userList = users[0];
$('#users').empty();
for(user in userList) { console.log(user);
if(userList[user].username == username) {
var row = '';
row += '<tr class="leaderboard-user-row"><td></td>';
row += '<td>'+userList[user].age+'</td>';
row += ... | identifier_body | |
main.js | }
var $usernameDiv = $('<span class="username"/>')
.text(timeNow() + " " + data.username)
.css('color', getUsernameColor(data.username));
var $messageBodyDiv = $('<span class="messageBody">')
.text(data.message);
var $messageDiv = $('<li class="message"/>')
.data('username', data.... |
for(user in userList) {
if(myEmpire.aspects['diplomacy'].quantity >= userList[user].territory)
{
$('.treaty').show();
showUserActions = true;
}
else
$('.treaty').hide();
}
if(myEmpire.aspects['army'].quantity > 0 ||
myEmpire.aspects['science'].quantity > 0 ||
... | {
$('.tradedeal').hide();
} | conditional_block |
main.js |
var userList = {};
var silentMode = false;
var quietMode = false;
var blockList = [];
// ------------ //
// private info //
// ------------ //
function MyAspect(name, shortening, level, quantity, maxsize) {
this.name = name;
this.shortening = shortening;
this.level = level;
this.quant... | var $currentInput = $usernameInput.focus();
var socket = io(); | random_line_split | |
main.js | ASPECT_NAMES[i];
if(myEmpire.aspects['science'].quantity >= discCost)
$('#lvlup_'+aspect).show();
else
$('#lvlup_'+aspect).hide();
if(myEmpire.aspects['development'].quantity >= builCost)
$('#upgrade_'+aspect).show();
else
$('#upgrade_'+aspect).hide();
}
// background o... | addActionDiv | identifier_name | |
main.py | 1
elif wybor == "3":
tekst = "który 'p' (max " + str(len(all_p)-1) + " element wyświetlić?:"
ktoryP = input(tekst)
print(ktoryP ," element: ",all_h1_tags, soup.select("p")[int(ktoryP)].text)
#endregion
#region 4-web-scraping-example5.py
def example5():
# Create top_items as empt... | if all_links[licznik]["href"].count("https") > 0:
adres = all_links[licznik]["href"]
elif all_links[licznik]["href"].count("#") > 0:
adres = domena + "/" + all_links[licznik]["href"]
else:
adres = domena + all_links[licznik]["href"]
... | n top_items according to instructions on the left
links = soup.select("a")
print("Liczba linków = ", len(links))
for ahref in links:
text = ahref.text
text = text.strip() if text is not None else ""
href = ahref.get("href")
href = href.strip() if href is not None else ""
... | identifier_body |
main.py | ():
# Create all_h1_tags as empty list
all_h1_tags = []
# Set all_h1_tags to all h1 tags of the soup
for element in soup.select("h1"):
all_h1_tags.append(element.text)
# Create seventh_p_text and set it to 7th p element text of the page
seventh_p_text = soup.select("p")[6].text
all... | example4 | identifier_name | |
main.py | 1
elif wybor == "3":
tekst = "który 'p' (max " + str(len(all_p)-1) + " element wyświetlić?:"
ktoryP = input(tekst)
print(ktoryP ," element: ",all_h1_tags, soup.select("p")[int(ktoryP)].text)
#endregion
#region 4-web-scraping-example5.py
def example5():
# Create top_items as empt... | nu:\n1.przykła z zajęć\n2.Wyświetl tytuły produktów\n3.Znajdź produkt po tytule")
wybor = input("twój wybór:")
if wybor == "1":
print(top_items)
elif wybor == "2":
print("sprawdźmy jakie produkty są: ")
licznik = 0
while licznik<len(top_items):
print(top_items[lic... | elect("h4 > a.title")[0].text
review_label = elem.select("div.ratings")[0].text
info = {"title": title.strip(), "review": review_label.strip()}
top_items.append(info)
print("me | conditional_block |
main.py | list
top_items = []
# Extract and store in top_items according to instructions on the left
products = soup.select("div.thumbnail")
print("Liczba top items = ", len(products))
for elem in products:
title = elem.select("h4 > a.title")[0].text
review_label = elem.select("div.ratings")... | # soup = BeautifulSoup(page.content, "html.parser")
soup = BeautifulSoup(html_doc, "lxml")
# Extract head of page | random_line_split | |
upimg.js | , id: 17 , name:'天天卤味' },
{parentId: 2, id: 18 , name:'小明烧菜' },
{parentId: 2, id: 19 , name:'麦德豪' },
{parentId: 2, id: 20 , name:'水果捞' },
{parentId: 3, id: 1 , name:'自选快餐' },
{parentId: 3, id: 2 , name:'风味早点' },
{parentId: 4, id: 1 , name:'特色煲仔' ... | {
show2:true,
store:that.data.proCityArr[1][that.data.proCityIndex[1]],
canteennum:e.detail.value.picker[0]+1,
talknum:0,
cainum:0,
isaudit:false,
img_name:that.data.inputvaule,
img_src: 'ht... | identifier_body | |
upimg.js | 先生渔粉' },
{parentId: 7, id: 9 , name:'沙茶面' },
{parentId: 7, id: 10 , name:'水果捞' },
{parentId: 7, id: 11 , name:'鑫龙福麻辣烫' },
{parentId: 7, id: 12 , name:'兰州拉面' },
{parentId: 7, id: 13 , name:'胖子' },
{parentId: 8, id: 1 , name:'迪卡健身餐厅' },
{parentId: 8... | identifier_name | ||
upimg.js | {parentId: 6, id: 2 , name:'阿妈香肉拌饭' },
{parentId: 6, id: 3 , name:'阿兴瓦罐' },
{parentId: 6, id: 4 , name:'典赞花甲粉' },
{parentId: 6, id: 5 , name:'广式煲仔砂锅' },
{parentId: 6, id: 6 , name:'麻辣香锅' },
{parentId: 6, id: 7 , name:'蜀合记' },
{parentId: 6, id: 8 , name:'无骨烤鱼饭' },
... | 新赋值
})
}else{//第二列选中项数据被滑动修改了...
proCityIndex[1] = index;
this.setData({
[`proCityIndex`]: | conditional_block | |
upimg.js | 18 , name:'兰州拉面' },
{parentId: 1, id: 19 , name:'锡纸烤' },
{parentId: 1, id: 20 , name:'嘿米牛肉饭' },
{parentId: 1, id: 21 , name:'猪脚饭' },
{parentId: 1, id: 22 , name:'豪客士' },
{parentId: 2, id: 1 , name:'99自助餐' },
{parentId: 2, id: 2 , name:'壹米阳光' },
{parentId:... | )
{
console.log('form发生了submit事件,携带数据为:', e.detail.value)
console.log('form发生了submit事件,食堂序号为:', e.detail.value.picker[0])
console.log('form发生了submit事件,店名为:',this.data.proCityArr[1][this.data.proCityIndex[1]])
| this.data.inputvaule!=''&&
this.data.details!='' | random_line_split |
train.py | 0].coef_)))
for i, est in enumerate(estimators):
coeffs[i] = est.coef_
fig = plt.figure(figsize=(5.5, 5))
ax = fig.add_subplot(111)
m1 = ax.imshow(coeffs.T, aspect='auto', origin='lower')
ax.set_title('Visualization of the linear regression coefficients')
ax.set_xlabel('Linear regressio... |
cs[f], p = spearmanr(x_train[:, f], np.mean(y_train, axis=1))
select = np.argsort(np.abs(cs))[np.max([-nb_feats, -len(cs)]):]
return select
@benchmark
def train_estimators(estimators, x_train, y_train):
for mel_bin in range(len(estimators)):
estimators[mel_bin].fit(x_train, y_train[:, me... | cs[f] = 0
continue | conditional_block |
train.py | [0].coef_)))
for i, est in enumerate(estimators):
coeffs[i] = est.coef_
fig = plt.figure(figsize=(5.5, 5))
ax = fig.add_subplot(111)
m1 = ax.imshow(coeffs.T, aspect='auto', origin='lower')
ax.set_title('Visualization of the linear regression coefficients')
ax.set_xlabel('Linear regressi... | # instead of 0.0016 as with the audio, resulting in 4 more frames. Cutting off in the
# beginning aligns the audio to the current frame.
# Quantize the logMel spectrogram
medians, borders, q_spectrogram = quantization(y_train, nb_intervals=9)
# F... | logger.info('No bad channels specified.')
x_train, y_train = compute_features(eeg, sfreq_eeg, audio, sfreq_audio)
y_train = y_train[20:-4] # Skip 24 samples too align the neural signals to the audio. 20 frames are needed to
# first to have all context for one sample. In a... | random_line_split |
train.py | 0].coef_)))
for i, est in enumerate(estimators):
coeffs[i] = est.coef_
fig = plt.figure(figsize=(5.5, 5))
ax = fig.add_subplot(111)
m1 = ax.imshow(coeffs.T, aspect='auto', origin='lower')
ax.set_title('Visualization of the linear regression coefficients')
ax.set_xlabel('Linear regressio... | (y_train, nb_intervals=8):
"""
Quantize the logMel spectrogram
"""
medians, borders = compute_borders_logistic(y_train, nb_intervals=nb_intervals)
q_spectrogram = quantize_spectrogram(y_train, borders)
# print if a spec bin does not contain samples for a interval
for i in range(q_spectrogra... | quantization | identifier_name |
train.py | 0].coef_)))
for i, est in enumerate(estimators):
coeffs[i] = est.coef_
fig = plt.figure(figsize=(5.5, 5))
ax = fig.add_subplot(111)
m1 = ax.imshow(coeffs.T, aspect='auto', origin='lower')
ax.set_title('Visualization of the linear regression coefficients')
ax.set_xlabel('Linear regressio... |
def train(eeg, audio, sfreq_eeg, sfreq_audio, bad_channels, nb_mel_bins=40):
# exclude bad channels
if len(bad_channels) > 0:
logger.info('EEG original shape: {} x {}'.format(*eeg.shape))
mask = np.ones(eeg.shape[1], bool)
mask[bad_channels] = False
eeg = eeg[:, mask]
... | x_train = herff2016_b(eeg, sfreq_eeg, 0.05, 0.01)
# resample audio to 16kHz
audio = decimate(audio, 3)
audio_sr = 16000
y_train = compute_spectrogram(audio, audio_sr, 0.016, 0.01)
return x_train, y_train | identifier_body |
mod.rs | // allocate some memory to write our instructions
let size = size * PAGE_SIZE;
let layout = Layout::from_size_align(size, PAGE_SIZE).unwrap();
let contents = unsafe {
let raw = alloc(layout);
write_bytes(raw, 0xc3, size);
libc::mprotect(raw as *mut libc::c_vo... | (instructions: &[Instruction]) -> Program {
// we'll emit something that respects x86_64 system-v:
// rdi (1st parameter): pointer to cell array
// rsi (2nd parameter): pointer to output function
// rdx (3rd parameter): pointer to WriteWrapper
// rcx (4th parameter): pointer to input function
//... | transform | identifier_name |
mod.rs | allocate some memory to write our instructions
let size = size * PAGE_SIZE;
let layout = Layout::from_size_align(size, PAGE_SIZE).unwrap();
let contents = unsafe {
let raw = alloc(layout);
write_bytes(raw, 0xc3, size);
libc::mprotect(raw as *mut libc::c_void,... |
pub fn as_mut_slice(&mut self) -> &mut [u8] {
unsafe { slice::from_raw_parts_mut(self.program.contents, self.program.size) }
}
pub fn lock(self) -> Program {
unsafe {
libc::mprotect(
self.program.contents as *mut libc::c_void,
self.program.size,... | {
unsafe { slice::from_raw_parts(self.program.contents, self.program.size) }
} | identifier_body |
mod.rs | // allocate some memory to write our instructions
let size = size * PAGE_SIZE;
let layout = Layout::from_size_align(size, PAGE_SIZE).unwrap();
let contents = unsafe {
let raw = alloc(layout);
write_bytes(raw, 0xc3, size);
libc::mprotect(raw as *mut libc::c_vo... | unsafe { slice::from_raw_parts_mut(self.program.contents, self.program.size) }
}
pub fn lock(self) -> Program {
unsafe {
libc::mprotect(
self.program.contents as *mut libc::c_void,
self.program.size,
libc::PROT_NONE,
);
... | }
pub fn as_mut_slice(&mut self) -> &mut [u8] { | random_line_split |
csv_orders_with_feedback.py | :return:
"""
# self.logger.debug('get tick data: %s', md_dic)
symbol = md_dic['symbol']
# 更新最新价格
close_cur = md_dic['close']
self.symbol_latest_price_dic[symbol] = close_cur
# 计算是否需要进行调仓操作
if self.symbol_target_position_dic is None or symbol not in self.... | random_line_split | ||
csv_orders_with_feedback.py | target_currency_set = set(list(position_df['currency']))
holding_currency_dic = self.get_holding_currency()
# 检查是否所有持仓符合目标配置文件要求
is_all_fit_target = True
# 如果当前 currency 不在目标持仓列表里面,则卖出
for num, (currency, balance_dic) in enumerate(holding_currency... | n_dic:
logging.debug("持仓数据中没有包含当前合约,最近一次成交回报时间:%s,跳过",
self.datetime_last_rtn_trade_dic[symbol])
self.get_position(symbol, force_refresh=True)
return
if self.datetime_last_rtn_trade_dic[symbol] > self.datetime_last_update_position... | identifier_body | |
csv_orders_with_feedback.py | hold_vol
def check_stop_loss(self, close):
"""
根据当前价格计算是否已经到达止损点位
如果此前已经到达过止损点位则不再比较,也不需重置状态
:param close:
:return:
"""
# 如果此前已经到达过止损点位则不再比较,也不需重置状态
if self.stop_loss_price is None or self.has_stop_loss:
return
self.has_stop_loss =... | ol = gap_thres | identifier_name | |
csv_orders_with_feedback.py | 币交易所的一种手续费代币工具,不做交易使用
# if currency == 'hc':
# continue
# 若持仓余额 小于 0.0001 则放弃清仓
tot_balance = 0
for _, dic in balance_dic.items():
tot_balance += dic['balance']
if tot_balance < 0.0001:
... | return
with self._mutex:
target_position = self.symbol_target_position_dic[symbol]
target_position.check_stop_loss(close_cur)
# self.logger.debug("当前持仓目标:%r", target_position)
# 撤销所有相关订单
self.cancel_order(symbol)
# 计算目标仓位方向及交易数量
... | conditional_block | |
types.go | ",
TypeLongBlob: "longBlob",
TypeBlob: "blob",
TypeVarString: "varString",
TypeString: "string",
TypeGeometry: "geometry",
}
func (t ColumnType) isNumeric() bool {
switch t {
case TypeTiny, TypeShort, TypeInt24, TypeLong, TypeLongLong,
TypeFloat, TypeDouble, TypeDecimal, TypeNewDecimal:
retur... |
func fractionalSecondsNegative(meta uint16, r *reader) (int, error) {
n := (meta + 1) / 2
v := int(bigEndian | {
n := (meta + 1) / 2
v := bigEndian(r.bytesInternal(int(n)))
return int(v * uint64(math.Pow(100, float64(3-n)))), r.err
} | identifier_body |
types.go | .Meta))
scale := int(byte(col.Meta >> 8))
buff := r.bytes(decimalSize(precision, scale))
if r.err != nil {
return nil, r.err
}
return decodeDecimal(buff, precision, scale)
case TypeFloat:
return math.Float32frombits(r.int4()), r.err
case TypeDouble:
return math.Float64frombits(r.int8()), r.err
case ... | decimalSize | identifier_name | |
types.go | 6) // unset sign bit
frac, err = fractionalSecondsNegative(col.Meta, r)
if err != nil {
return nil, err
}
if frac == 0 && sec < 59 { // weird duration behavior
sec++
}
} else {
frac, err = fractionalSeconds(col.Meta, r)
if err != nil {
return nil, err
}
}
v := time.Duration(ho... | {
var buf bytes.Buffer
err := json.NewEncoder(&buf).Encode(s.Members())
return buf.Bytes(), err
} | conditional_block | |
types.go | .Minute +
time.Duration(sec)*time.Second +
time.Duration(frac)*time.Microsecond
if sign == 0 {
v = -v
}
return v, r.err
case TypeYear:
v := int(r.int1())
if v == 0 {
return 0, r.err
}
return 1900 + v, r.err
}
return nil, fmt.Errorf("decode of mysql type %s is not implemented", col.Type)
}
... |
// BigFloat returns the number as a *big.Float. | random_line_split | |
raft.go | < rf.lastIncludedIndex {
reply.Success = false
reply.NextIndex = lastIndex + 1
return
}
if args.PrevLogIndex+len(args.Entries) <= rf.CommitIndex {
reply.Success = false
reply.NextIndex = rf.CommitIndex + 1
return
}
var lastTerm int
if len(rf.Log) == 0 || args.PrevLogIndex < rf.Log[0].Index {
lastTer... | return
}
if args.Term > rf.CurrentTerm {
rf.VotedFor = -1
rf.CurrentTerm = args.Term
rf.identity = FOLLOWER
}
if rf.VotedFor != -1 && rf.VotedFor != args.CandidateId {
reply.VoteGranted = false
return
}
var rfLogIndex int
var rfLogTerm int
if len(rf.Log) > 0 {
rfLogIndex = rf.Log[len(rf.Log)-1].... | if args.Term < rf.CurrentTerm {
reply.VoteGranted = false | random_line_split |
raft.go | AppendEntries(index, args, &reply)
}(i, args)
} else {
var args InstallSnapshotArgs
args.Term = rf.CurrentTerm
args.LeaderId = rf.me
args.LastIncludedIndex = rf.lastIncludedIndex
args.LastIncludedTerm = rf.lastIncludedTerm
args.Snapshot = rf.persister.ReadSnapshot()
go func(index int,... | TakeSnapshot | identifier_name | |
raft.go |
func (rf *Raft) RaftStateSize() int {
return rf.persister.RaftStateSize()
}
//
// save Raft's persistent state to stable storage,
// where it can later be retrieved after a crash and restart.
// see paper's Figure 2 for a description of what should be persistent.
//
func (rf *Raft) persist() {
// Your code here.
... | {
return rf.CurrentTerm, rf.identity == LEADER
} | identifier_body | |
raft.go | , args AppendEntriesArgs) {
var reply AppendEntriesReply
rf.sendAppendEntries(index, args, &reply)
}(i, args)
} else {
var args InstallSnapshotArgs
args.Term = rf.CurrentTerm
args.LeaderId = rf.me
args.LastIncludedIndex = rf.lastIncludedIndex
args.LastIncludedTerm = rf.lastIncludedT... | {
//fmt.Println("peer", rf.me, "apply entry", i)
//fmt.Println("peer", rf.me, "'s commitIndex:", rf.CommitIndex)
rf.lastApplied = i
var args ApplyMsg
args.Index = i
//if rf.IsLeader() {
// fmt.Println("Leader")
//}
//fmt.Println(rf.Log)
//fmt.Println("i:", i)
//fmt.Println("rf.Log[0].I... | conditional_block | |
kinematics.py | < 0 :
angle = 2*np.pi - angle
return angle
return None
# Manages distances on a polynomial chain
class Polychain(object) :
# floating point precision
HVERSOR = np.array([1,0])
def set_chain(self, chain) :
'''
chain (array): each row is a point (x,y)
... | (self, distance) :
'''
get a point in the 2D space given a
distance from the first point of the chain
'''
if distance > 1 :
raise ValueError('distance must be a proportion of the polyline length (0,1)')
distance = sum(self.seg_lens)*distance
cum_ln... | get_point | identifier_name |
kinematics.py | < 0 :
angle = 2*np.pi - angle
return angle
return None
# Manages distances on a polynomial chain
class Polychain(object) :
# floating point precision
HVERSOR = np.array([1,0])
def set_chain(self, chain) :
'''
chain (array): each row is a point (x,y)
... |
#----------------------------------------------------------------------
#----------------------------------------------------------------------
#----------------------------------------------------------------------
#----------------------------------------------------------------------
# ARM --------------------... | '''
return: the length of the current polyline
'''
return sum(self.seg_lens) | identifier_body |
kinematics.py | < 0 :
angle = 2*np.pi - angle
return angle
return None
# Manages distances on a polynomial chain
class Polychain(object) :
# floating point precision
HVERSOR = np.array([1,0])
def set_chain(self, chain) :
'''
chain (array): each row is a point (x,y)
... | """
number_of_joint: (int) number of joints
joint_angles (list): initial joint angles
joint_lims (list): joint angles limits
segment_lengths (list): length of arm segmens
origin (list): origin coords of arm
"""
... | mirror = False
): | random_line_split |
kinematics.py | # Manages distances on a polynomial chain
class Polychain(object) :
# floating point precision
HVERSOR = np.array([1,0])
def set_chain(self, chain) :
'''
chain (array): each row is a point (x,y)
of the polygonal chain
'''
# ensure ... | res_joint_angles = -res_joint_angles
res_joint_angles[0] += np.pi | conditional_block | |
modeltranslator.go | .Process = *process
*dbSpans = append(*dbSpans, dbSpan)
}
}
return nil
}
func (c *Translator) spanWithoutProcess(span pdata.Span) (*dbmodel.Span, error) {
if span.IsNil() {
return nil, nil
}
traceID, err := convertTraceID(span.TraceID())
if err != nil {
return nil, err
}
spanID, err := convertSpanID(s... | {
return dbmodel.KeyValue{}, false
} | conditional_block | |
modeltranslator.go |
// ConvertSpans converts spans from OTEL model to Jaeger Elasticsearch model
func (c *Translator) ConvertSpans(traces pdata.Traces) ([]*dbmodel.Span, error) {
rss := traces.ResourceSpans()
if rss.Len() == 0 {
return nil, nil
}
dbSpans := make([]*dbmodel.Span, 0, traces.SpanCount())
for i := 0; i < rss.Len(); i... | {
tagsKeysAsFieldsMap := map[string]bool{}
for _, v := range tagsKeysAsFields {
tagsKeysAsFieldsMap[v] = true
}
return &Translator{
allTagsAsFields: allTagsAsFields,
tagKeysAsFields: tagsKeysAsFieldsMap,
tagDotReplacement: tagDotReplacement,
}
} | identifier_body | |
modeltranslator.go | traceID,
SpanID: spanID,
// Since Jaeger RefType is not captured in internal data,
// use SpanRefType_FOLLOWS_FROM by default.
// SpanRefType_CHILD_OF supposed to be set only from parentSpanID.
RefType: dbmodel.FollowsFrom,
})
}
return refs, nil
}
func convertSpanID(spanID pdata.SpanID) (dbmodel.S... | tag.Value = strconv.FormatInt(attr.IntVal(), 10)
case pdata.AttributeValueDOUBLE:
tag.Type = dbmodel.Float64Type
tag.Value = strconv.FormatFloat(attr.DoubleVal(), 'g', 10, 64)
} | random_line_split | |
modeltranslator.go | }
references, err := references(span.Links(), span.ParentSpanID(), traceID)
if err != nil {
return nil, err
}
startTime := toTime(span.StartTime())
startTimeMicros := model.TimeAsEpochMicroseconds(startTime)
tags, tagMap := c.tags(span)
return &dbmodel.Span{
TraceID: traceID,
SpanID: spanI... | logs | identifier_name | |
bosh_exporter.go | .uaa.client-secret", "",
"BOSH UAA Client Secret ($BOSH_EXPORTER_BOSH_UAA_CLIENT_SECRET).",
)
boshLogLevel = flag.String(
"bosh.log-level", "ERROR",
"BOSH Log Level ($BOSH_EXPORTER_BOSH_LOG_LEVEL).",
)
boshCACertFile = flag.String(
"bosh.ca-cert-file", "",
"BOSH CA Certificate file ($BOSH_EXPORTER_BOSH_... | }
uaaConfig, err := uaa.NewConfigFromURL(uaaURLStr)
if err != nil {
return nil, err
}
uaaConfig.CACert = boshCACert
if *boshUAAClientID != "" && *boshUAAClientSecret != "" {
uaaConfig.Client = *boshUAAClientID
uaaConfig.ClientSecret = *boshUAAClientSecret
} else {
uaaConfig.Client = "bosh_c... | random_line_split | |
bosh_exporter.go | .uaa.client-secret", "",
"BOSH UAA Client Secret ($BOSH_EXPORTER_BOSH_UAA_CLIENT_SECRET).",
)
boshLogLevel = flag.String(
"bosh.log-level", "ERROR",
"BOSH Log Level ($BOSH_EXPORTER_BOSH_LOG_LEVEL).",
)
boshCACertFile = flag.String(
"bosh.ca-cert-file", "",
"BOSH CA Certificate file ($BOSH_EXPORTER_BOSH_... |
logger := logger.NewLogger(logLevel)
directorConfig, err := director.NewConfigFromURL(*boshURL)
if err != nil {
return nil, err
}
boshCACert, err := readCACert(*boshCACertFile, logger)
if err != nil {
return nil, err
}
directorConfig.CACert = boshCACert
anonymousDirector, err := director.NewFactory(lo... | {
return nil, err
} | conditional_block |
bosh_exporter.go | .uaa.client-secret", "",
"BOSH UAA Client Secret ($BOSH_EXPORTER_BOSH_UAA_CLIENT_SECRET).",
)
boshLogLevel = flag.String(
"bosh.log-level", "ERROR",
"BOSH Log Level ($BOSH_EXPORTER_BOSH_LOG_LEVEL).",
)
boshCACertFile = flag.String(
"bosh.ca-cert-file", "",
"BOSH CA Certificate file ($BOSH_EXPORTER_BOSH_... | (CACertFile string, logger logger.Logger) (string, error) {
if CACertFile != "" {
fs := system.NewOsFileSystem(logger)
CACertFileFullPath, err := fs.ExpandPath(CACertFile)
if err != nil {
return "", err
}
CACert, err := fs.ReadFileString(CACertFileFullPath)
if err != nil {
return "", err
}
ret... | readCACert | identifier_name |
bosh_exporter.go | filter.collectors", "",
"Comma separated collectors to filter (Deployments,Jobs,ServiceDiscovery) ($BOSH_EXPORTER_FILTER_COLLECTORS).",
)
metricsNamespace = flag.String(
"metrics.namespace", "bosh",
"Metrics Namespace ($BOSH_EXPORTER_METRICS_NAMESPACE).",
)
metricsEnvironment = flag.String(
"metrics.envir... | {
flag.Parse()
overrideFlagsWithEnvVars()
if *showVersion {
fmt.Fprintln(os.Stdout, version.Print("bosh_exporter"))
os.Exit(0)
}
log.Infoln("Starting bosh_exporter", version.Info())
log.Infoln("Build context", version.BuildContext())
boshClient, err := buildBOSHClient()
if err != nil {
log.Errorf("Erro... | identifier_body | |
main.py | (Gammes[0]))
if afficher_commentaires: print("arcrouge ",(indice_pièceETmachine,indice_fin));
A[indice_pièceETmachine][indice_fin] = Valeur[NOLINK][1]
return A
#question1
def GRAPHE(s,gamme = Gammes,afficher_commentaires=False):
#j'initialise le graphe et j'ajoute les arcs, verts, rouge e... | seurs(Graphe,v)
auplustard[v] = min([ auplustard[w] - t(Graphe, v,w) for w in N_plus])
return auplustard
Gammes= [ [1,2,3],[2 | conditional_block | |
main.py | première_machine = trouver_indice_machine_dans_la_gamme(Gammes,indice_pièce, 0);
indice_pièceETmachine = trouver_indice_couple(indice_pièce,première_machine,len(Gammes),len(Gammes[0]) )
if afficher_commentaires: print("arc vert ",(indice_debut,indice_pièceETmachine));
A[indice_debut][i... | = 2 + len(Gammes)*len(Gammes[0])
taille_matrice = nb_noeuds
A = np.full((taille_matrice,taille_matrice),NOLINK)
#la même pièce i passe par des machines j: arcs noirs
for i in range(len(Gammes)):
for j in range (len(Gammes[0])-1): #on parcours les machines sauf la dernière
pièce ... | identifier_body | |
main.py | arcs noirs
for i in range(len(Gammes)):
for j in range (len(Gammes[0])-1): #on parcours les machines sauf la dernière
pièce = i + 1;indice_pièce = i
indice_machine1 = trouver_indice_machine_dans_la_gamme(Gammes,indice_pièce, j)
indice_machine2 = trouver_indice_machine_d... | :
#j'initialise le graphe et j'ajoute les arcs, verts, rouge et noirs
graphe = fct_Matrice_Adjacence(gamme,afficher_commentaires)
#je m'assure que la solution et la gamme sont deux matrices
if 2+ len(s)*len(s[0]) != len(graphe):
print("erreur: le nombre de ligne de la gamme doit être égal a... | False) | identifier_name |
main.py | : arcs noirs
for i in range(len(Gammes)):
for j in range (len(Gammes[0])-1): #on parcours les machines sauf la dernière
pièce = i + 1;indice_pièce = i
indice_machine1 = trouver_indice_machine_dans_la_gamme(Gammes,indice_pièce, j)
indice_machine2 = trouver_indice_machine_... | liste_plc = PLC(G,sommet_depart=0)
indice_piece = i-1; indice_machine= j-1
indice_pièceETmachine = trouver_indice_couple(indice_piece,indice_machine,len(S[0]),len(S))
return liste_plc[indice_pièceETmachine]
print("plc(2,1)= ", plc(2,1))
print("fin question 2", end = "\n\n\n\n\n")
Gammes= [ [1,2,3],[2... | random_line_split | |
file_system.rs | /// Whether DirEntries added to this filesystem should be considered permanent, instead of a
/// cache of the backing storage. An example is tmpfs: the DirEntry tree *is* the backing
/// storage, as opposed to ext4, which uses the DirEntry tree as a cache and removes unused
/// nodes from it.
pub pe... |
Ok(stat)
}
pub fn did_create_dir_entry(&self, entry: &DirEntryHandle) {
if self.permanent_entries {
self.entries.lock().insert(Arc::as_ptr(entry) as usize, entry.clone());
}
}
pub fn will_destroy_dir_entry(&self, entry: &DirEntryHandle) {
if self.permanent_... | {
stat.f_frsize = stat.f_bsize as i64;
} | conditional_block |
file_system.rs | ,
/// Whether DirEntries added to this filesystem should be considered permanent, instead of a
/// cache of the backing storage. An example is tmpfs: the DirEntry tree *is* the backing
/// storage, as opposed to ext4, which uses the DirEntry tree as a cache and removes unused
/// nodes from it.
pub... | /// Returns `ENOSYS` if the `FileSystemOps` don't implement `stat`.
pub fn statfs(&self) -> Result<statfs, Errno> {
let mut stat = self.ops.statfs(self)?;
if stat.f_frsize == 0 {
stat.f_frsize = stat.f_bsize as i64;
}
Ok(stat)
}
pub fn did_create_dir_entry(&s... | ///
/// Each `FileSystemOps` impl is expected to override this to return the specific statfs for
/// the filesystem.
/// | random_line_split |
file_system.rs | ,
/// Whether DirEntries added to this filesystem should be considered permanent, instead of a
/// cache of the backing storage. An example is tmpfs: the DirEntry tree *is* the backing
/// storage, as opposed to ext4, which uses the DirEntry tree as a cache and removes unused
/// nodes from it.
pub... | (&self) -> &DirEntryHandle {
self.root.get().unwrap()
}
/// Get or create an FsNode for this file system.
///
/// If inode_num is Some, then this function checks the node cache to
/// determine whether this node is already open. If so, the function
/// returns the existing FsNode. If no... | root | identifier_name |
file_system.rs | /// Whether DirEntries added to this filesystem should be considered permanent, instead of a
/// cache of the backing storage. An example is tmpfs: the DirEntry tree *is* the backing
/// storage, as opposed to ext4, which uses the DirEntry tree as a cache and removes unused
/// nodes from it.
pub pe... |
fn new_internal(
kernel: &Kernel,
ops: impl FileSystemOps,
permanent_entries: bool,
) -> FileSystemHandle {
Arc::new(FileSystem {
root: OnceCell::new(),
next_inode: AtomicU64::new(1),
ops: Box::new(ops),
dev_id: kernel.device_regi... | {
if root.inode_num == 0 {
root.inode_num = self.next_inode_num();
}
root.set_fs(self);
let root_node = Arc::new(root);
self.nodes.lock().insert(root_node.inode_num, Arc::downgrade(&root_node));
let root = DirEntry::new(root_node, None, FsString::new());
... | identifier_body |
agent.go | agent release and version information.
type RInfo struct {
// InstanceID the unique name identificator for this agent
InstanceID string
// Version is the app X.Y.Z version
Version string
// Commit is the git commit sha1
Commit string
// Branch is the git branch
Branch string
// BuildStamp is the build timesta... | log.Infof("Device %s finished", cfg.ID)
// If device goroutine has finished, leave the bus so it won't get blocked trying
// to send messages to a not running device.
dev.LeaveBus(Bus)
}()
mutex.Unlock()
}
// LoadConf loads the DB conf and initializes the device metric config.
func LoadConf() {
MainConfig.D... | defer gatherWg.Done()
dev.StartGather() | random_line_split |
agent.go | agent release and version information.
type RInfo struct {
// InstanceID the unique name identificator for this agent
InstanceID string
// Version is the app X.Y.Z version
Version string
// Commit is the git commit sha1
Commit string
// Branch is the git branch
Branch string
// BuildStamp is the build timesta... |
// End stops all devices polling.
func End() (time.Duration, error) {
start := time.Now()
log.Infof("END: begin device Gather processes stop... at %s", start.String | {
LoadConf()
DeviceProcessStart()
} | identifier_body |
agent.go | agent release and version information.
type RInfo struct {
// InstanceID the unique name identificator for this agent
InstanceID string
// Version is the app X.Y.Z version
Version string
// Commit is the git commit sha1
Commit string
// Branch is the git branch
Branch string
// BuildStamp is the build timesta... | else {
log.Printf("SELFMON disabled %+v\n", MainConfig.Selfmon)
}
}
// IsDeviceInRuntime checks if device `id` exists in the runtime array.
func IsDeviceInRuntime(id string) bool {
mutex.Lock()
defer mutex.Unlock()
if _, ok := devices[id]; ok {
return true
}
return false
}
// DeleteDeviceInRuntime removes ... | {
if val, ok := idb["default"]; ok {
// only executed if a "default" influxdb exist
val.Init()
val.StartSender(&senderWg)
selfmonProc.Init()
selfmonProc.SetOutDB(idb)
selfmonProc.SetOutput(val)
log.Printf("SELFMON enabled %+v", MainConfig.Selfmon)
// Begin the statistic reporting
selfmonP... | conditional_block |
agent.go | agent release and version information.
type RInfo struct {
// InstanceID the unique name identificator for this agent
InstanceID string
// Version is the app X.Y.Z version
Version string
// Commit is the git commit sha1
Commit string
// Branch is the git branch
Branch string
// BuildStamp is the build timesta... | () bool {
reloadMutex.Lock()
defer reloadMutex.Unlock()
retval := reloadProcess
reloadProcess = true
return retval
}
// CheckAndUnSetReloadProcess unsets the reloadProcess flag.
// Returns its previous value.
func CheckAndUnSetReloadProcess() bool {
reloadMutex.Lock()
defer reloadMutex.Unlock()
retval := reloa... | CheckAndSetReloadProcess | identifier_name |
arena.rs | the reference count.
///
/// # Safety
///
/// `handle` must be allocated from `self`.
// TODO: If we wrap `ArrayPtr::r` with `SpinlockProtected`, then we can just use `clone` instead.
unsafe fn dup(&self, handle: &Ref<Self::Data>) -> Ref<Self::Data>;
/// Deallocate a given handle, and fina... |
}
impl<T, const CAPACITY: usize> MruArena<T, CAPACITY> {
// TODO(https://github.com/kaist-cp/rv6/issues/371): unsafe...
pub const fn new(entries: [MruEntry<T>; CAPACITY]) -> Self {
Self {
entries,
list: unsafe { List::new() },
}
}
pub fn init(self: Pin<&mut Sel... | {
(list_entry as *const _ as usize - Self::LIST_ENTRY_OFFSET) as *const Self
} | identifier_body |
arena.rs | the reference count.
///
/// # Safety
///
/// `handle` must be allocated from `self`.
// TODO: If we wrap `ArrayPtr::r` with `SpinlockProtected`, then we can just use `clone` instead.
unsafe fn dup(&self, handle: &Ref<Self::Data>) -> Ref<Self::Data>;
/// Deallocate a given handle, and fina... |
}
}
empty.map(|cell_raw| {
// SAFETY: `cell` is not referenced or borrowed. Also, it is already pinned.
let mut cell = unsafe { Pin::new_unchecked(&mut *cell_raw) };
n(cell.as_mut().get_pin_mut().unwrap().get_mut());
cell.borrow()
})
... | {
return Some(r);
} | conditional_block |
arena.rs | <F: FnOnce(&mut Self::Data)>(&self, f: F) -> Option<Rc<Self>> {
let inner = self.alloc_handle(f)?;
// SAFETY: `inner` was allocated from `self`.
Some(unsafe { Rc::from_unchecked(self, inner) })
}
/// Duplicate a given handle, and increase the reference count.
///
/// # Safety
... | alloc | identifier_name | |
arena.rs | the reference count.
///
/// # Safety
///
/// `handle` must be allocated from `self`.
// TODO: If we wrap `ArrayPtr::r` with `SpinlockProtected`, then we can just use `clone` instead.
unsafe fn dup(&self, handle: &Ref<Self::Data>) -> Ref<Self::Data>;
/// Deallocate a given handle, and fina... |
impl<T> MruEntry<T> {
// TODO(https://github.com/kaist-cp/rv6/issues/369)
// A workarond for https://github.com/Gilnaa/memoffset/issues/49.
// Assumes `list_entry` is located at the beginning of `MruEntry`
// and `data` is located at `mem::size_of::<ListEntry>()`.
const DATA_OFFSET: usize = mem::si... | {
guard.reacquire_after(f)
}
} | random_line_split |
driver.rs | serial_ports::{ListPortInfo, ListPorts};
use serial_ports::ListPortType::UsbPort;
use tokio_core::reactor::Handle;
use tokio_core::channel::channel;
use tokio_core::channel::Sender;
use tokio_core::channel::Receiver;
use config::Config;
use errors::*;
use item::Item;
use device::DB;
#[cfg(windows)]
fn get_default... |
}
// The following should be removed, once we have all of the devices captured using the above
let default_devices = ["/dev/cu.usbserial", // MacOS X (presumably)
"/dev/cu.SLAB_USBtoUART", // MacOS X (Aeotech Z-Stick S2)
"/dev/cu.u... | {
error!("[OpenzwaveStateful] {:04x}:{:04x} {}",
info.vid,
info.pid,
port.device.display());
} | conditional_block |
driver.rs | serial_ports::{ListPortInfo, ListPorts};
use serial_ports::ListPortType::UsbPort;
use tokio_core::reactor::Handle;
use tokio_core::channel::channel;
use tokio_core::channel::Sender;
use tokio_core::channel::Receiver;
use config::Config;
use errors::*;
use item::Item;
use device::DB;
#[cfg(windows)]
fn get_default... | (handle: &Handle, cfg: &Config) -> Result<(ZWave, Receiver<Notification<Item>>)> {
let cfg = cfg.clone();
let mut manager = {
let config_path = match cfg.sys_config {
Some(ref path) => path.as_ref(),
None => "/etc/openzwave",
};
let u... | new | identifier_name |
driver.rs | serial_ports::{ListPortInfo, ListPorts};
use serial_ports::ListPortType::UsbPort;
use tokio_core::reactor::Handle;
use tokio_core::channel::channel;
use tokio_core::channel::Sender;
use tokio_core::channel::Receiver;
use config::Config;
use errors::*;
use item::Item;
use device::DB;
#[cfg(windows)]
fn get_default... |
}
impl Binding for ZWave {
type Config = Config;
type Error = Error;
type Item = Item;
fn new(handle: &Handle, cfg: &Self::Config) -> Result<(Self, Receiver<Notification<Item>>)> {
ZWave::new(handle, cfg)
}
fn get_value(&self, name: &str) -> Option<Item> {
always_lock(self.it... | {
always_lock(self.ozw_manager.lock())
} | identifier_body |
driver.rs | Info) -> bool {
let default_usb_devices = [// VID PID
// ----- -----
(0x0658, 0x0200), // Aeotech Z-Stick Gen-5
(0x0658, 0x0280), // UZB1
(0x10c4, 0xea60) /* Aeotech Z-Stick S2 */];
... | Some(s) => s,
None => { | random_line_split | |
array-virtual-repeat-strategy.ts | lices replace existing entries?
// this means every removal of collection item is followed by an added with the same count
let allSplicesAreInplace = true;
for (i = 0; spliceCount > i; i++) {
splice = splices[i];
const removedCount = splice.removed.length;
const addedCount = splice.addedCo... | updateAllViews | identifier_name | |
array-virtual-repeat-strategy.ts | (splice => splice.index <= firstIndex);
if (all_splices_are_positive_and_before_view_port) {
repeat.$first = firstIndex + totalAddedCount - 1;
repeat.topBufferHeight += totalAddedCount * itemHeight;
// 1. ensure that change in scroll position will not be ignored
repeat.enableScroll();
... | random_line_split | ||
array-virtual-repeat-strategy.ts | splice.index <= firstIndex);
if (all_splices_are_positive_and_before_view_port) {
repeat.$first = firstIndex + totalAddedCount - 1;
repeat.topBufferHeight += totalAddedCount * itemHeight;
// 1. ensure that change in scroll position will not be ignored
repeat.enableScroll();
// 2. ch... | {
first_index_after_scroll_adjustment = Math$max(0, newArraySize - newViewCount);
} | conditional_block | |
array-virtual-repeat-strategy.ts |
initCalculation(repeat: IVirtualRepeater, items: any[]): VirtualizationCalculation {
const itemCount = items.length;
// when there is no item, bails immediately
// and return false to notify calculation finished unsuccessfully
if (!(itemCount > 0)) {
return VirtualizationCalculation.reset;
... | {
return items.length;
} | identifier_body | |
fit_sed.py | ):
"""Switch method for different types of flux measurement input.
Returns 2d array of floats. Note that first column can be an exact
observed central wavelength, or a number in [70, 100, 160, ...],
which serves as a proxy for pacs-blue, or pacs-green, etc.
"""
if isinstance(measurements, base... | observed wavelengths in microns
f_nu : 1d array
observed flux density in mJy
"""
waves, L_nu = read_K15_template(template)
# observed wavelengths
waves *= (1 + z)
cosmo = FlatLambdaCDM(H0=70, Om0=0.3)
D_L = cosmo.luminosity_distance(z)
# flux density [m... |
Returns
-------
waves : 1d array | random_line_split |
fit_sed.py | ):
"""Switch method for different types of flux measurement input.
Returns 2d array of floats. Note that first column can be an exact
observed central wavelength, or a number in [70, 100, 160, ...],
which serves as a proxy for pacs-blue, or pacs-green, etc.
"""
if isinstance(measurements, base... |
else:
sys.exit('Incorrect PACS filter entered.')
elif 'spire' in telescope_filter:
pass
else:
sys.exit('"{}"" is not supported.'.format(telescope_filter))
clean_measurements[i, 0] = float(observed_wavelength)
t... | observed_wavelength = 160 | conditional_block |
fit_sed.py | ):
"""Switch method for different types of flux measurement input.
Returns 2d array of floats. Note that first column can be an exact
observed central wavelength, or a number in [70, 100, 160, ...],
which serves as a proxy for pacs-blue, or pacs-green, etc.
"""
if isinstance(measurements, base... | (template):
"""Reads in a K15 template SED, returning an array of
wavelength and corresponding array of specific luminosity."""
template_fname = os.path.join(root_dir, 'data', 'kirkpatrick+15',
'Comprehensive_library', '{}.txt'.format(template))
if not os.path.isfile(template_fname)... | read_K15_template | identifier_name |
fit_sed.py | ):
"""Switch method for different types of flux measurement input.
Returns 2d array of floats. Note that first column can be an exact
observed central wavelength, or a number in [70, 100, 160, ...],
which serves as a proxy for pacs-blue, or pacs-green, etc.
"""
if isinstance(measurements, base... | return chi2, norm
else:
if verbose:
print('Template {} unsuccessful.'.format(template))
return np.nan, np.nan
def calculate_uncertainties(norm, modeled_fluxes, measured_fluxes,
measured_uncertainties, nsteps=500, nwalkers=100, nburnin=50,
nthreads=4, save_samples=Fal... | assert template in K15_SED_templates
# get and unpack redshifted wavelengths and SED
waves, f_nu = model_sed(template, z)
# unpack measurements and then model what they should be
measured_waves, measured_fluxes, measured_uncertainties = measurements.T
modeled_fluxes = np.array([model_photometry(w... | identifier_body |
utils.rs | ;
use winapi::um::handleapi::CloseHandle;
use winapi::um::memoryapi::ReadProcessMemory;
use winapi::um::processthreadsapi::OpenProcess;
use winapi::um::psapi::GetModuleFileNameExW;
use winapi::um::shlobj::SHGetKnownFolderPath;
use winapi::um::winbase::{FORMAT_MESSAGE_ALLOCATE_BUFFER, FORMAT_MESSAGE_FROM_SYSTEM, FormatM... |
pub unsafe fn get_executable_description(exe: &Path) -> Result<String, ()> {
let exe_utf16 = exe.to_str().unwrap().to_utf16_null();
let mut handle: DWORD = 0;
let size = GetFileVersionInfoSizeW(exe_utf16.as_ptr(), &mut handle);
if size == 0 {
error!("GetFileVersionInfoSizeW, err={}, exe={}", ... | {
let process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
if process == null_mut() {
return Err(Error::new("OpenProcess").into());
};
let _close_process = close_handle(process);
let mut name = [0u16; 32 * 1024];
let length = GetModuleFileNameExW(process, null_mut(), na... | identifier_body |
utils.rs |
use itertools::Itertools;
use log::error;
use ntapi::ntpebteb::PEB;
use ntapi::ntpsapi::{NtQueryInformationProcess, PROCESS_BASIC_INFORMATION, ProcessBasicInformation};
use ntapi::ntrtl::RTL_USER_PROCESS_PARAMETERS;
use winapi::shared::guiddef::GUID;
use winapi::shared::minwindef::{BOOL, DWORD, FALSE, LPARAM, TRUE};
u... | use std::path::{Path, PathBuf};
use std::ptr::{null, null_mut}; | random_line_split | |
utils.rs | to_utf16_null(&self) -> Vec<u16>;
}
impl StrExt for &str {
fn to_utf16_null(&self) -> Vec<u16> {
let mut v: Vec<_> = self.encode_utf16().collect();
v.push(0);
v
}
}
pub fn check_error() -> wrapperrs::Result<()> {
format_error(unsafe { GetLastError() })
}
pub fn format_error(err: ... | collect_requester_info | identifier_name | |
mod.rs | }
// One of two endpoints for a control channel with a connector on either end.
// The underlying transport is TCP, so we use an inbox buffer to allow
// discrete payload receipt.
struct NetEndpoint {
inbox: Vec<u8>,
stream: TcpStream,
}
// Datastructure used during the setup phase representing a NetEndpoint ... | Equivalent,
New(Predicate),
Nonexistant, | random_line_split | |
mod.rs | (element).is_ok()
}
// Insert the given element. Returns whether it was already present.
fn insert(&mut self, element: T) -> bool {
match self.vec.binary_search(&element) {
Ok(_) => false,
Err(index) => {
self.vec.insert(index, element);
true
... | {
return Err(Ace::WrongPortPolarity { port, expected_polarity });
} | conditional_block | |
mod.rs | a duplicate port,
/// or if the component is unfit for instantiation with the given port sequence.
/// # Panics
/// This function panics if the connector's (large) component id space is exhausted.
pub fn add_component(
&mut self,
module_name: &[u8],
identifier: &[u8],
po... | fmt | identifier_name | |
mod.rs | }
// Similar to `PortInfo`, but designed for communication during the setup procedure.
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
struct MyPortInfo {
polarity: Polarity,
port: PortId,
owner: ComponentId,
}
// Newtype around port info map, allowing the implementation of some
// useful me... | {
Self {
connector_id,
port_suffix_stream: Default::default(),
component_suffix_stream: Default::default(),
}
} | identifier_body | |
zkdevice.py | sys
import telnetlib
def get_server_ip(device_ip):
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((device_ip, 80))
return s.getsockname()[0]
def transfer_file(from_ip, to_ip, remote_file_path, cmd='ftpput'):
'''
Transfer file from from_ip to to_ip via telnet.
... |
add_log(uid, date, 'in')
add | delete_log(log[0]) | conditional_block |
zkdevice.py | .read_until(b'#'):
s.write(bytes('ls %s\n' % DB_PATH, 'utf-8'))
files = s.read_until(b'#').decode()
if filename in files:
while True:
if cmd == 'ftpput':
command = bytes('%s -P 2121 %s %s %s\n' % (cmd, server_ip,
... | start, end = args.range.split('-')
transfer_file(DEVICE_IP, server_ip, DB_PATH, cmd='ftpput')
| random_line_split | |
zkdevice.py | sys
import telnetlib
def get_server_ip(device_ip):
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((device_ip, 80))
return s.getsockname()[0]
def transfer_file(from_ip, to_ip, remote_file_path, cmd='ftpput'):
'''
Transfer file from from_ip to to_ip via telnet.
... | (uid, start, end, status, late=False):
start_date = datetime.datetime.strptime(start, '%d/%m/%Y')
end_date = datetime.datetime.strptime(end, '%d/%m/%Y')
day_count = end_date - start_date
day_count = day_count.days + 1
for date in (start_date + datetime.timedelta(i) for i in range(day_count)):
... | add_logs | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.