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 |
|---|---|---|---|---|
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.
... |
def check_log_row(log_row):
'''
Each day must have exactly 2 logs.
One for checking in, before 8:00:00
One for checking out, after 17:00:00
Return True if satisfies all conditions, else False
'''
in_time = datetime.time(8, 0, 0)
out_time = datetime.time(17, 0, 0)
log_date = datet... | '''
Pretty print a log row
log row format: (ID, User_PIN, Verify_Type, Verify_Time, Status)
'''
id, uid, verify_type, verify_time, status = log_row
if status == 1:
status = 'Check out'
elif status == 0:
status = 'Check in'
print('{}. {} {} at {}'.format(id, uid, status, veri... | identifier_body |
obj.rs | ///
/// Returns the symbol associated with the function as well as the range
/// that the function resides within the text section.
pub fn append_func(
&mut self,
name: &str,
compiled_func: &'a CompiledFunction<impl CompiledFuncEnv>,
resolve_reloc_target: impl Fn(FuncInde... | /// within `CompiledFunction` and the return value must be an index where
/// the target will be defined by the `n`th call to `append_func`. | random_line_split | |
obj.rs | self.unwind_info.push(off, body_len, info);
}
for r in compiled_func.relocations() {
match r.reloc_target {
// Relocations against user-defined functions means that this is
// a relocation against a module-local function, typically a
... | {
let body = compiled_func.buffer.data();
let alignment = compiled_func.alignment;
let body_len = body.len() as u64;
let off = self
.text
.append(true, &body, alignment, &mut self.ctrl_plane);
let symbol_id = self.obj.add_symbol(Symbol {
name:... | identifier_body | |
obj.rs | compiled_func.buffer.data();
let alignment = compiled_func.alignment;
let body_len = body.len() as u64;
let off = self
.text
.append(true, &body, alignment, &mut self.ctrl_plane);
let symbol_id = self.obj.add_symbol(Symbol {
name: name.as_bytes().to_... | (&mut self) {
self.text.force_veneers();
}
/// Appends the specified amount of bytes of padding into the text section.
///
/// This is only useful when fuzzing and/or debugging cranelift itself and
/// for production scenarios `padding` is 0 and this function does nothing.
pub fn append... | force_veneers | identifier_name |
obj.rs | compiled_func.buffer.data();
let alignment = compiled_func.alignment;
let body_len = body.len() as u64;
let off = self
.text
.append(true, &body, alignment, &mut self.ctrl_plane);
let symbol_id = self.obj.add_symbol(Symbol {
name: name.as_bytes().to_... |
for r in compiled_func.relocations() {
match r.reloc_target {
// Relocations against user-defined functions means that this is
// a relocation against a module-local function, typically a
// call between functions. The `text` field is given priority ... | {
self.unwind_info.push(off, body_len, info);
} | conditional_block |
util.rs | Listener;
use tokio::timer::{Delay, Interval};
use crate::task::Task;
use crate::Float;
use crate::{AGG_ERRORS, DROPS, EGRESS, INGRESS, INGRESS_METRICS, PARSE_ERRORS, PEER_ERRORS};
use bioyino_metric::{name::MetricName, Metric, MetricType};
use crate::{ConsensusState, CONSENSUS_STATE, IS_LEADER};
pub fn prepare_log(... | <F: IntoFuture> {
action: F,
inner: Either<F::Future, Delay>,
options: BackoffRetryBuilder,
}
impl<F> Future for BackoffRetry<F>
where
F: IntoFuture + Clone,
{
type Item = F::Item;
type Error = Option<F::Error>;
fn poll(&mut self) -> Poll<Self | BackoffRetry | identifier_name |
util.rs | TcpListener;
use tokio::timer::{Delay, Interval};
use crate::task::Task;
use crate::Float;
use crate::{AGG_ERRORS, DROPS, EGRESS, INGRESS, INGRESS_METRICS, PARSE_ERRORS, PEER_ERRORS};
use bioyino_metric::{name::MetricName, Metric, MetricType};
use crate::{ConsensusState, CONSENSUS_STATE, IS_LEADER};
pub fn prepare_l... | if self.interval > 0 {
let s_interval = self.interval as f64 / 1000f64;
info!(self.log, "stats";
"egress" => format!("{:2}", egress / s_interval),
"ingress" => format!("{:2}", ingress / s_interval),
"ingress-m" => format!("{:2}", ingress_m / s_interva... | add_metric!(INGRESS_METRICS, ingress_m, "ingress-metric");
add_metric!(AGG_ERRORS, agr_errors, "agg-error");
add_metric!(PARSE_ERRORS, parse_errors, "parse-error");
add_metric!(PEER_ERRORS, peer_errors, "peer-error");
add_metric!(DROPS, drops, "drop"); | random_line_split |
util.rs | Listener;
use tokio::timer::{Delay, Interval};
use crate::task::Task;
use crate::Float;
use crate::{AGG_ERRORS, DROPS, EGRESS, INGRESS, INGRESS_METRICS, PARSE_ERRORS, PEER_ERRORS};
use bioyino_metric::{name::MetricName, Metric, MetricType};
use crate::{ConsensusState, CONSENSUS_STATE, IS_LEADER};
pub fn prepare_log(... |
}
#[cfg(test)]
pub(crate) fn new_test_graphite_name(s: &'static str) -> MetricName {
let mut intermediate = Vec::new();
intermediate.resize(9000, 0u8);
let mode = bioyino_metric::name::TagFormat::Graphite;
MetricName::new(s.into(), mode, &mut intermediate).unwrap()
}
// A future to send own stats. N... | {
let is_leader = IS_LEADER.load(Ordering::SeqCst);
if is_leader != acquired {
warn!(log, "leader state change: {} -> {}", is_leader, acquired);
}
IS_LEADER.store(acquired, Ordering::SeqCst);
} | conditional_block |
util.rs | Listener;
use tokio::timer::{Delay, Interval};
use crate::task::Task;
use crate::Float;
use crate::{AGG_ERRORS, DROPS, EGRESS, INGRESS, INGRESS_METRICS, PARSE_ERRORS, PEER_ERRORS};
use bioyino_metric::{name::MetricName, Metric, MetricType};
use crate::{ConsensusState, CONSENSUS_STATE, IS_LEADER};
pub fn prepare_log(... |
}
impl BackoffRetryBuilder {
pub fn spawn<F>(self, action: F) -> BackoffRetry<F>
where
F: IntoFuture + Clone,
{
let inner = Either::A(action.clone().into_future());
BackoffRetry { action, inner, options: self }
}
}
/// TCP client that is able to reconnect with customizable set... | {
Self {
delay: 500,
delay_mul: 2f32,
delay_max: 10000,
retries: 25,
}
} | identifier_body |
listing.rs | String};
use crate::archive::CompressionMethod;
use crate::errors::{self, ContextualError};
use crate::renderer;
use crate::themes::ColorScheme;
/// Query parameters
#[derive(Deserialize)]
pub struct QueryParameters {
pub path: Option<PathBuf>,
pub sort: Option<SortingMethod>,
pub order: Option<SortingOrd... | (&self) -> bool {
self.entry_type == EntryType::Directory
}
/// Returns whether the entry is a file
pub fn is_file(&self) -> bool {
self.entry_type == EntryType::File
}
/// Returns whether the entry is a symlink
pub fn is_symlink(&self) -> bool {
self.entry_type == Entr... | is_dir | identifier_name |
listing.rs | String};
use crate::archive::CompressionMethod;
use crate::errors::{self, ContextualError};
use crate::renderer;
use crate::themes::ColorScheme;
/// Query parameters
#[derive(Deserialize)]
pub struct QueryParameters {
pub path: Option<PathBuf>,
pub sort: Option<SortingMethod>,
pub order: Option<SortingOrd... | /// Type of the entry
pub entry_type: EntryType,
/// URL of the entry
pub link: String,
/// Size in byte of the entry. Only available for EntryType::File
pub size: Option<bytesize::ByteSize>,
/// Last modification date
pub last_modification_date: Option<SystemTime>,
}
impl Entry {
... | /// Entry
pub struct Entry {
/// Name of the entry
pub name: String,
| random_line_split |
masking.py | -------
Tuple[MaskingSchema, MaskedTargets]
"""
# TODO : Add option to predict N-last items
# shift sequence of item-ids
labels = item_ids[:, 1:]
# As after shifting the sequence length will be subtracted by one, adding a masked item in
# the sequence to return t... | if self.eval_on_last_item_seq_only:
last_item_sessions = tf.reduce_sum(non_padded_mask, axis=1) - 1
indices = tf.concat(
[
tf.expand_dims(rows_ids, 1),
tf.cast(tf.expand_dims(last_item_sessions, 1), tf.int64),
... | conditional_block | |
masking.py | hide) their positions in the sequence so that they are not used by the Transformer
layers for prediction.
We currently provide 4 different masking schemes out of the box:
- Causal LM (clm)
- Masked LM (mlm)
- Permutation LM (plm)
- Replacement Token Detection (rtd)
This cla... | (self, item_ids: tf.Tensor, training=False) -> MaskingInfo:
"""
Method to prepare masked labels based on the sequence of item ids.
It returns The true labels of masked positions and the related boolean mask.
And the attributes of the class `mask_schema` and `masked_targets`
are u... | compute_masked_targets | identifier_name |
masking.py | hide) their positions in the sequence so that they are not used by the Transformer
layers for prediction.
We currently provide 4 different masking schemes out of the box:
- Causal LM (clm)
- Masked LM (mlm)
- Permutation LM (plm)
- Replacement Token Detection (rtd)
This cla... |
def _compute_masked_targets(self, item_ids: tf.Tensor, training=False) -> MaskingInfo:
"""
Method to prepare masked labels based on the sequence of item ids.
It returns The true labels of masked positions and the related boolean mask.
Parameters
----------
item_ids... | super(MaskSequence, self).__init__(**kwargs)
self.padding_idx = padding_idx
self.eval_on_last_item_seq_only = eval_on_last_item_seq_only
self.mask_schema = None
self.masked_targets = None | identifier_body |
masking.py | hide) their positions in the sequence so that they are not used by the Transformer
layers for prediction.
We currently provide 4 different masking schemes out of the box:
- Causal LM (clm)
- Masked LM (mlm)
- Permutation LM (plm)
- Replacement Token Detection (rtd)
This cla... | """
Method to prepare masked labels based on the sequence of item ids.
It returns The true labels of masked positions and the related boolean mask.
Parameters
----------
item_ids: tf.Tensor
The sequence of input item ids used for deriving labels of
... | random_line_split | |
app.rs | State;
use super::util::PeriodicEvent;
use skulpin_renderer::LogicalSize;
use skulpin_renderer::Size;
use skulpin_renderer::RendererBuilder;
use skulpin_renderer::CoordinateSystem;
use skulpin_renderer::CoordinateSystemHelper;
use skulpin_renderer::ValidationMode;
use skulpin_renderer::rafx::api::RafxError;
use crate:... | match *self {
AppError::RafxError(ref e) => e.fmt(fmt),
AppError::WinitError(ref e) => e.fmt(fmt),
}
}
}
impl From<RafxError> for AppError {
fn from(result: RafxError) -> Self {
AppError::RafxError(result)
}
}
impl From<winit::error::OsError> for AppError {
... | fn fmt(
&self,
fmt: &mut core::fmt::Formatter,
) -> core::fmt::Result { | random_line_split |
app.rs | (Debug)]
pub enum AppError {
RafxError(skulpin_renderer::rafx::api::RafxError),
WinitError(winit::error::OsError),
}
impl std::error::Error for AppError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match *self {
AppError::RafxError(ref e) => Some(e),
Ap... | {} | conditional_block | |
app.rs | ;
use super::util::PeriodicEvent;
use skulpin_renderer::LogicalSize;
use skulpin_renderer::Size;
use skulpin_renderer::RendererBuilder;
use skulpin_renderer::CoordinateSystem;
use skulpin_renderer::CoordinateSystemHelper;
use skulpin_renderer::ValidationMode;
use skulpin_renderer::rafx::api::RafxError;
use crate::rafx... | (result: winit::error::OsError) -> Self {
AppError::WinitError(result)
}
}
pub struct AppUpdateArgs<'a, 'b, 'c> {
pub app_control: &'a mut AppControl,
pub input_state: &'b InputState,
pub time_state: &'c TimeState,
}
pub struct AppDrawArgs<'a, 'b, 'c, 'd> {
pub app_control: &'a AppControl,... | from | identifier_name |
lds.pb.go | d, 0x2c, 0x4d, 0x2d, 0x2e, 0x91, 0x52, 0xc1, 0xaf, 0xa8, 0xb8,
0x20, 0x3f, 0xaf, 0x38, 0x55, 0x89, 0x41, 0x83, 0xd1, 0x80, 0x51, 0x28, 0x82, 0x8b, 0x3f, 0xb8,
0xa4, 0x28, 0x35, 0x31, 0x17, 0x61, 0x87, 0x1c, 0x9a, 0x76, 0x74, 0xe3, 0xe5, 0x71, 0xca, 0xa3,
0x98, 0x5c, 0xcd, 0xc5, 0xe7, 0x96, 0x5a, 0x92, 0x9c, 0x41, 0x... | {
s.RegisterService(&_ListenerDiscoveryService_serviceDesc, srv)
} | identifier_body | |
lds.pb.go | Stream.
type ListenerDiscoveryServiceClient interface {
DeltaListeners(ctx context.Context, opts ...grpc.CallOption) (ListenerDiscoveryService_DeltaListenersClient, error)
StreamListeners(ctx context.Context, opts ...grpc.CallOption) (ListenerDiscoveryService_StreamListenersClient, error)
FetchListeners(ctx context.... | random_line_split | ||
lds.pb.go | nil
}
func (c *listenerDiscoveryServiceClient) FetchListeners(ctx context.Context, in *DiscoveryRequest, opts ...grpc.CallOption) (*DiscoveryResponse, error) {
out := new(DiscoveryResponse)
err := c.cc.Invoke(ctx, "/envoy.api.v2.ListenerDiscoveryService/FetchListeners", in, out, opts...)
if err != nil {
return n... | {
return 0, ErrIntOverflowLds
} | conditional_block | |
lds.pb.go | (b []byte) error {
return m.Unmarshal(b)
}
func (m *LdsDummy) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_LdsDummy.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return... | XXX_Unmarshal | identifier_name | |
chat.js | * 生命周期函数--监听页面显示
*/
onShow: function() {
var that = this;
if (!socketOpen) {
that.webSocket()
}
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function() {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function() {
},
/**
* 连接websocket
*
*/
webSocket... | /**
* 获取聚焦
*/
focus: function(e) {
keyHeight = e.detail.height;
this.setData({
scrollHeight: (windowHeight - keyHeight) + 'px'
});
this.setData({
toView: 'msg-' + (msgList.length - 1),
inputBottom: keyHeight + 'px'
})
},
//失去聚焦(软键盘消失)
blur: function(e) {
this.s... | },
| random_line_split |
chat.js | 生命周期函数--监听页面显示
*/
onShow: function() {
var that = this;
if (!socketOpen) {
that.webSocket()
}
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function() {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function() {
},
/**
* 连接websocket
*
*/
webSocket: ... | success: function(res) {},
fail: function(err) {
wx.showToast({
title: '网络异常!',
})
console.log(err)
},
})
that.initWebsocket();
} else if (res.data.status == 402) {
w... | image: '../../images/hint1.png',
mask: true,
})
setTimeout(function () {
//要延时执行的代码
wx.navigateBack({
delta: 1
});
}, 1000)
}
that.setData({
myOpenId:... | conditional_block |
chat.js | !',
})
console.log(err)
},
})
that.initWebsocket();
} else if (res.data.status == 402) {
wx.showToast({
title: res.data.msg,
image: '../../images/hint2.png',
mask: true,
})
... | ime));
}
} else {
msg.format | identifier_body | |
chat.js | 生命周期函数--监听页面显示
*/
onShow: function() {
var that = this;
if (!socketOpen) {
that.webSocket()
}
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function() {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function() {
},
/**
* 连接websocket
*
*/
webSocket: ... | header: {
"Content-Type": "multipart/form-data",
'Authorization': token // 缓存中token信息
},
success: function (res) {
var data = JSON.parse(res.data);
if(data.status==200){
var msg = {
msgType: 2,
conten... | ile',
| identifier_name |
neexe.rs | {
pub linker_major_version: u8,
pub linker_minor_version: u8,
pub entry_table_offset: u16,
pub entry_table_size: u16,
pub crc: u32,
pub flags: NEFlags,
pub auto_data_segment_index: u16,
pub heap_size: u16,
pub stack_size: ... | NEHeader | identifier_name | |
neexe.rs | u16,
pub module_table_offset: u16,
pub import_names_table_offset: u16,
pub non_resident_table_offset: u32,
pub num_movable_entry_point: u16,
pub alignment_shift_count: u16, // 1 << alignment_shift_count = logical sector
pub num_resources: u16,
pub target_os: u8,
p... | min_code_swap_size: le_u16 >>
win_version_minor: le_u8 >>
win_version_major: le_u8 >>
(NEHeader {
linker_major_version,
linker_minor_version,
entry_table_offset,
entry_table_size,
crc,
flags: NEFlags::from_bits_truncate(flags),
auto_data_segment_index,
heap_size,
... | segment_thunk_offset: le_u16 >> | random_line_split |
neexe.rs | PlugPlay = 19,
VXD = 20,
AnimatedCursor = 21,
AnimatedIcon = 22,
HTML = 23,
Manifest = 24,
}
}
#[derive(Clone, Debug)]
pub enum NEResourceId {
Integer(u16),
String(String),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum NEResourceKind {
Predefined(NEPr... | {
NEResourcesIterator::new(&self.raw_header[self.header.resource_table_offset as usize..])
} | conditional_block | |
query-builder-common.js | -list li").draggable('disable');
$("#reset").removeClass("reset disabled-link").addClass("reset rotate");
}
});
// Enable slim scroll bar for table
enableSlimScroll($(".query-builder"), {
height : "410px"
});
$("[data-toggle='tooltip']").tooltip({
placement : "top"
});
}
/**... | tolerance : "touch",
accept : ".table-column-list-container",
drop : function(event, ui) { | random_line_split | |
query-builder-common.js | i').addClass('fa-minus-square')
.removeClass('fa-plus-square');
}
e.stopPropagation();
});
});
fetchAllTablesAjax(loadTablesInTree);
enableDeleteTable();
enableTableSearch();
showExpressionBuilder();
function showExpressionBuilder(){
loadExpressionBuilder();
$(".... | () {
$('#new-link-line').remove();
$(document).unbind('mousemove.link').unbind('click.link').unbind('keydown.link');
}
/**
* Load operators in select box
* @param results
*/
function loadOperatorsInSelectBox(results){
$(".pop-modal-content").find(".operators_select_box").each(function(){
$(this).dds... | endLinkMode | identifier_name |
query-builder-common.js | else {
children.show('fast');
$(this).attr('title', 'Collapse this branch').find(
' > i').addClass('fa-minus-square')
.removeClass('fa-plus-square');
}
e.stopPropagation();
});
});
fetchAllTablesAjax(loadTables... | {
children.hide('fast');
$(this).attr('title', 'Expand this branch').find(
' > i').addClass('fa-plus-square')
.removeClass('fa-minus-square');
} | conditional_block | |
query-builder-common.js | i').addClass('fa-minus-square')
.removeClass('fa-plus-square');
}
e.stopPropagation();
});
});
fetchAllTablesAjax(loadTablesInTree);
enableDeleteTable();
enableTableSearch();
showExpressionBuilder();
function showExpressionBuilder(){
loadExpressionBuilder();
$(".... |
var connections = [];
var connectionsId = [];
//connections.push(new $.connect('#PROD2CAT', '#PRODUKT', {leftLabel : 'Many', rightLabel: 'One'}));
/**
* Here we enable the drag and drop events for drag the tables and drop into drop area with list of columns
*/
function enableDNDEvents() {
var zIndex = 3;
$... | {
$(".pop-modal-content").find(".operators_select_box").each(function(){
$(this).ddslick({
data : results,
width : 170
});
});
} | identifier_body |
http.go | )
// Request struct for Search POST
type SearchRequest struct {
Services []string
MovieName string
}
// Request struct for get downloads links POST
type DownloadLinksRequest struct {
Service string
Movie m.Movie
}
// Response struct for Search Request
type FoundMovies struct {
Service string
... | "time" | random_line_split | |
http.go | directory traversal
path, err := filepath.Abs(r.URL.Path)
if err != nil {
// if we failed to get the absolute path respond with a 400 bad request
// and stop
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// prepend the path with the path to the static directory
path = filepath... |
func StopTorrent(ip string, ID string) bool {
out, err := exec.Command("/usr/bin/transmission-remote", ip,"-t", ID, "-S").Output()
if err != nil {
log.Fatal(err)
return false
}
if strings.Contains(string(out), "Error") {
return false
} else {
return true
}
}
func ResumeTorrent(ip string, ID string) boo... | {
out, err := exec.Command("/usr/bin/transmission-remote", ip,"-a", magnetLink).Output()
if err != nil {
log.Fatal(err)
return false
}
if strings.Contains(string(out), "Error") {
return false
} else {
return true
}
} | identifier_body |
http.go | directory traversal
path, err := filepath.Abs(r.URL.Path)
if err != nil {
// if we failed to get the absolute path respond with a 400 bad request
// and stop
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// prepend the path with the path to the static directory
path = filepath... | (w http.ResponseWriter, r *http.Request) {
// Set Header for Options
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "*")
fmt.Printf("[%s] - Requested listServices\n", time.Now().Format("2006-01-02 15:04:05"))
var listServices []string
for key, ... | listServices | identifier_name |
http.go | directory traversal
path, err := filepath.Abs(r.URL.Path)
if err != nil |
// prepend the path with the path to the static directory
path = filepath.Join(h.staticPath, path)
// check whether a file exists at the given path
_, err = os.Stat(path)
if os.IsNotExist(err) {
// file does not exist, serve index.html
http.ServeFile(w, r, filepath.Join(h.staticPath, h.indexPath))
r... | {
// if we failed to get the absolute path respond with a 400 bad request
// and stop
http.Error(w, err.Error(), http.StatusBadRequest)
return
} | conditional_block |
gologs.go | 0, b.c)
// NOTE: This logic allows for a race between two threads that both get the
// time for an event, then race for the mutex below that serializes output
// to the underlying io.Writer. While not dangerous, the logic might allow
// two log lines to be emitted to the writer in opposite timestamp order.
if b.i... |
// SetWarning changes the log level to Warning, which causes all Debug, Verbose,
// and Info events to be ignored, and all Warning, and Error events to be
// logged.
func (b *Logger) SetWarning() *Logger {
atomic.StoreUint32((*uint32)(&b.level), uint32(Warning))
return b
}
// SetError changes the log level to Erro... | {
atomic.StoreUint32((*uint32)(&b.level), uint32(Info))
return b
} | identifier_body |
gologs.go | (e *event) error {
// ??? *If* want to sacrifice a bit of speed, might consider using a
// pre-allocated byte slice to format the output. The pre-allocated slice
// can be protected with the lock already being used to serialize output, or
// even better, its own lock so one thread can be formatting an event while
... | log | identifier_name | |
gologs.go | 0, b.c)
// NOTE: This logic allows for a race between two threads that both get the
// time for an event, then race for the mutex below that serializes output
// to the underlying io.Writer. While not dangerous, the logic might allow
// two log lines to be emitted to the writer in opposite timestamp order.
if b.i... |
return buf[:1] // all newline characters, so just return the first one
}
type logger interface {
log(*event) error
}
// Logger provides methods to create events to be logged. Logger instances are
// created to emit events to their parent Logger instance, which may themselves
// either filter events based on a con... | {
if buf[i] != '\n' {
if i+1 < l && buf[i+1] == '\n' {
return buf[:i+2]
}
return append(buf[:i+1], '\n')
}
} | conditional_block |
gologs.go | 0, b.c)
// NOTE: This logic allows for a race between two threads that both get the
// time for an event, then race for the mutex below that serializes output
// to the underlying io.Writer. While not dangerous, the logic might allow
// two log lines to be emitted to the writer in opposite timestamp order.
if b.... | if b.prefix != "" {
e.prefix = append([]string{b.prefix}, e.prefix...)
}
return b.parent.log(e)
}
// SetLevel allows changing the log level. Events must have the same log level
// or higher for events to be logged.
func (b *Logger) SetLevel(level Level) *Logger {
atomic.StoreUint32((*uint32)(&b.level), uint32(le... | random_line_split | |
gui_LMI.py | Click)
self.bAxiSave.clicked.connect(self.bAxiSaveClick)
#---历史数据界面按钮
self.bExport.clicked.connect(self.bExportClick)
#---QT界面数据刷新线程
self.thread = MyThread()
self.thread.setIdent... | dictPara['tLDip']=self.tLDip.toPlainText()
dictPara['tRUip']=self.tRUip.toPlainText()
dictPara['tRDip']=self.tRDip.toPlainText()
dictPara['tC1ip']=self.tC1ip.toPlainText()
dictPara['tC2ip']=self.tC2ip.toPlainText()
dictPara['tSpeed']=self.tSpeed.t... | dictPara['tBadRate']=self.tBadRate.toPlainText()
dictPara['tFail']=self.tFail.toPlainText()
dictPara['tLUip']=self.tLUip.toPlainText() | random_line_split |
gui_LMI.py | PLC.on("100",8)
# time.sleep(0.1)
# PLC.off("100",8)
pass
#---红灯
def bRedClick(self):
global flag,rf
flag=1
if rf==0:
PLC.on("100",9)
rf=1
flag=0
return 0
if rf==1:
PLC.off("100",... | raise ValueError("invalid thread id")
elif res != 1:
# """if it returns a number greater than one, you're in trouble,
# and you should call it again with exc=NULL to revert the effect"""
pythonapi.PyThreadState_SetAsyncExc(tid, None) | identifier_body | |
gui_LMI.py | Para['tBad']=self.tBad.toPlainText()
dictPara['tBadRate']=self.tBadRate.toPlainText()
dictPara['tFail']=self.tFail.toPlainText()
dictPara['tLUip']=self.tLUip.toPlainText()
dictPara['tLDip']=self.tLDip.toPlainText()
dictPara['tRUip']=self.tRUip.toPlainText() ... | time.sleep(1)
if __name__ == | conditional_block | |
gui_LMI.py | ip'],2005)
sockNr=socketClient.connect(dictPara['tC2ip'],2006)
except Exception as e:
print(str(e))
# PLC.openSerial()
#---事件
def closeEvent(self, event):
global ctrMelfaRxM
try:
pass
except:
pass
s... | 程功能
| identifier_name | |
mgmt.py | function": show_help,
"help": "Display help information for the specified command (e.g. mgmt.exe help set_log_level)",
},
### SETTINGS ###
# Add self to system path
"add_mgmt_to_system_path": {
"function": RegistrySettings.add_mgmt_utility_to_path,
"help": "Add the path to the m... | "show_lock_screen_widget": { | random_line_split | |
mgmt.py | return False
help_msg = cmd_parts["help"]
if help_msg is None:
p("}}rnNo Help Provided! " + param1 + "}}xx", log_level=1)
return False
p("}}yb" + help_msg + "}}xx")
return True
valid_commands = {
"help": {
"function": show_help,
"help": "Displa... | global LOGGER, valid_commands
# Find the help key for this command
cmd = util.get_param(1).lower()
param1 = util.get_param(2).lower()
if cmd == "" or param1 == "":
# Missing required parameters!
p("}}rnMissing Required Parameters! " + cmd + " - " + param1 + "}}xx", log_level=1)
... | identifier_body | |
mgmt.py | ():
ver = CredentialProcess.get_mgmt_version()
p("}}gbVersion: " + str(ver) + "}}xx")
return True
def show_help():
global LOGGER, valid_commands
# Find the help key for this command
cmd = util.get_param(1).lower()
param1 = util.get_param(2).lower()
if cmd == "" or param1 == "":
... | show_version | identifier_name | |
mgmt.py | "help": "A device changed (plugged in?) - do the appropriate steps to keep system secure (fired as event from OPEService)"
},
# If any nics aren't in the approved list, disable them
"scan_nics": {
"function": NetworkDevices.scan_nics,
"help": "Scan for nics that aren't approved and turn the... | p("}}rnERROR - Command not avaialable " + cmd + " - coming soon...}}xx", log_level=1)
sys.exit(1) | conditional_block | |
ClientMobileApp.js | import React, { Fragment, useRef, useEffect, useState } from 'react';
import { Link, withRouter } from 'react-router-dom';
import Tilt from 'react-tilt'
import RatingStars from './RatingStars';
import { useStoreState, useStoreDispatch } from 'easy-peasy';
import { logout } from '../../redux/actions/authActions';
... | useEffect(() => {
if(isUserAuth && role === "cliente") {
animateNumber(
userScoreRef.current,
0,
userScore,
3000,
setShowPercentage
);
}
}, [role, isUserAuth])
const playBeep ... | {
const userScoreRef = useRef(null);
// const [showMoreBtn, setShowMoreBtn] = useState(false);
const [showPercentage, setShowPercentage] = useState(false);
let { isUserAuth, role, loyaltyScores, userName } = useStoreState(state => ({
isUserAuth: state.authReducer.cases.isUserAuthenticat... | identifier_body |
ClientMobileApp.js | import React, { Fragment, useRef, useEffect, useState } from 'react';
import { Link, withRouter } from 'react-router-dom';
import Tilt from 'react-tilt'
import RatingStars from './RatingStars';
import { useStoreState, useStoreDispatch } from 'easy-peasy';
import { logout } from '../../redux/actions/authActions';
... | {loading
? (
<LoadingThreeDots color="white" />
) : (
)}
*/
/*
<div className="my-3 container-center">
<img src="/img/official-logo.jpg" alt="logo" width={300} height="auto"/>
</div>
*/ | }
export default withRouter(ClientMobileApp);
/*
| random_line_split |
ClientMobileApp.js | import React, { Fragment, useRef, useEffect, useState } from 'react';
import { Link, withRouter } from 'react-router-dom';
import Tilt from 'react-tilt'
import RatingStars from './RatingStars';
import { useStoreState, useStoreDispatch } from 'easy-peasy';
import { logout } from '../../redux/actions/authActions';
... | ({ history }) {
const userScoreRef = useRef(null);
// const [showMoreBtn, setShowMoreBtn] = useState(false);
const [showPercentage, setShowPercentage] = useState(false);
let { isUserAuth, role, loyaltyScores, userName } = useStoreState(state => ({
isUserAuth: state.authReducer.cases.isU... | ClientMobileApp | identifier_name |
ClientMobileApp.js | import React, { Fragment, useRef, useEffect, useState } from 'react';
import { Link, withRouter } from 'react-router-dom';
import Tilt from 'react-tilt'
import RatingStars from './RatingStars';
import { useStoreState, useStoreDispatch } from 'easy-peasy';
import { logout } from '../../redux/actions/authActions';
... |
}, [role, isUserAuth])
const playBeep = () => {
// Not working
const elem = document.querySelector("#appBtn");
elem.play();
}
const showLogin = () => (
<div className="my-5">
<div className="mb-3 text-white text-em-2-5 text-center text-default">
... | {
animateNumber(
userScoreRef.current,
0,
userScore,
3000,
setShowPercentage
);
} | conditional_block |
DanXuanCiHui.js | `spoken `,
`talked `
],
answer: "A"
},
{
question: `While I was in the university, I learned taking a photo, is very useful now for me. `,
options: [`it `, `which `, `that `, ` what`],
answer: "B"
},
{
question: `On average, a successful lawyer ha... | `who `,
`whose `,
`what`
], | random_line_split | |
trans_dist_mmei_v1_batch.py | each fastq take reads, reverse and trim them down to the last 17 bp. Then map to refseq_query or revcom of that
# if it maps to location on query, then it's RL, and trans_dist is location + 17 - spacer_end
# if it maps to location on query revcom, it's LR, then trans_dist is len refseq - location -17 + 5 - spacer_en... | (code, psl, description, filename, direction, refseq, spacer, date, excel, plot, plot_overlap): # main analysis function
# map spacer to refseq and determine query window
query_length = 500
if refseq.find(spacer) >= 0:
spacer_end = refseq.find(spacer) + 32
query = refseq[spacer_end-90:... | dist_find | identifier_name |
trans_dist_mmei_v1_batch.py | + 12, 11, str(example_reads_rl[i]), red_font)
logsheet.write(11, 12, "Example Reads LR", bold)
for i in range(0, query_length):
logsheet.write(i + 12, 12, str(example_reads_lr[i]), blue_font)
# 'highlight box', take from top_3 list determined above
logsheet.write(0,... | print("WARNING - File Not Found For {}".format(code)) | conditional_block | |
trans_dist_mmei_v1_batch.py | each fastq take reads, reverse and trim them down to the last 17 bp. Then map to refseq_query or revcom of that
# if it maps to location on query, then it's RL, and trans_dist is location + 17 - spacer_end
# if it maps to location on query revcom, it's LR, then trans_dist is len refseq - location -17 + 5 - spacer_en... | total += 1
rev_seq = record.seq.reverse_complement()
new_seq = rev_seq[len(rev_seq)-17:] # trim to last 17 base pair
if query.find(new_seq) >= 0: # corresponds to RL
trans_dist = query.find(new_seq) + 17 - spacer_end # distance in bp from end of protospacer
... | query_length = 500
if refseq.find(spacer) >= 0:
spacer_end = refseq.find(spacer) + 32
query = refseq[spacer_end-90:spacer_end+query_length] # '-99' accounts for the -50bp of the on-target later
query_rc = query.reverse_complement()
spacer_end = 90 # resets spacer end index to ... | identifier_body |
hashed.rs | : (0, 0),
pos: 0,
// keys: owned_self.clone().map(|x| &x.keys[..]), // &self.keys,
child: self.vals.cursor_from(0, 0),
}
}
}
}
/// An entry in hash tables.
#[derive(Debug, Clone)]
pub struct Entry<K: HashOrdered> {
/// The contained key.
key: K,
lower1: u32,
upper1: u32,
}
impl<K: HashOrdered> E... |
}
fn push_merge(&mut self, other1: (&Self::Trie, usize, usize), other2: (&Self::Trie, usize, usize)) -> usize {
// just rebinding names to clarify code.
let (trie1, mut lower1, upper1) = other1;
let (trie2, mut lower2, upper2) = other2;
debug_assert!(upper1 <= trie1.keys.len());
debug_assert!(upper2 <... | {
let other_basis = other.lower(lower); // from where in `other` the offsets do start.
let self_basis = self.vals.boundary(); // from where in `self` the offsets must start.
for index in lower .. upper {
let other_entry = &other.keys[index];
let new_entry = if other_entry.is_some() {
Entry::new(
... | conditional_block |
hashed.rs | as usize}
fn _set_lower(&mut self, x: usize) { self.lower1 = x as u32; }
fn set_upper(&mut self, x: usize) { self.upper1 = x as u32; }
}
/// Assembles a layer of this
pub struct HashedBuilder<K: HashOrdered, L> {
temp: Vec<Entry<K>>, // staging for building; densely packed here and then re-laid out in self.keys.... | {
HashedBuilder {
temp: Vec::with_capacity(cap),
keys: Vec::with_capacity(cap),
vals: L::with_capacity(cap),
}
} | identifier_body | |
hashed.rs | : (0, 0),
pos: 0,
// keys: owned_self.clone().map(|x| &x.keys[..]), // &self.keys,
child: self.vals.cursor_from(0, 0),
}
}
}
}
/// An entry in hash tables.
#[derive(Debug, Clone)]
pub struct Entry<K: HashOrdered> {
/// The contained key.
key: K,
lower1: u32,
upper1: u32,
}
impl<K: HashOrdered> E... | (other1: &Self::Trie, other2: &Self::Trie) -> Self {
HashedBuilder {
temp: Vec::new(),
keys: Vec::with_capacity(other1.keys() + other2.keys()),
vals: L::with_capacity(&other1.vals, &other2.vals),
}
}
/// Copies fully formed ranges (note plural) of keys from another trie.
///
/// While the ranges are fu... | with_capacity | identifier_name |
hashed.rs | ()),
vals: L::with_capacity(&other1.vals, &other2.vals),
}
}
/// Copies fully formed ranges (note plural) of keys from another trie.
///
/// While the ranges are fully formed, the offsets in them are relative to the other trie, and
/// must be corrected. These keys must be moved immediately to self.keys, as t... | } | random_line_split | |
views.py | if request.method == 'POST':
registerForm = RegisterForm(request.POST,request.FILES)#POST是校验普通字段,FILES是校验上传字段
if registerForm.is_valid():
#1.获取数据,cleaned_data 就是读取表单返回的值,返回类型为字典dict型
data = registerForm.cleaned_data
username = data.get('username')
nicknam... |
"""第三步主页"""
import datetime
#过滤器不能直接过滤时间戳
#给主页加一个装饰器
# @login_decorator
def index(request):
# 1.获取当前登录时间
times = datetime.datetime.now()
# 2. 获取头像
seller_id = request.session.get('seller_id')
seller_obj = models.Seller.objects.get(id=seller_id)
# models.Seller.objects.get(name=request.ses... | return redirect('/seller/login/')
return inner
| random_line_split |
views.py | if request.method == 'POST':
registerForm = RegisterForm(request.POST,request.FILES)#POST是校验普通字段,FILES是校验上传字段
if registerForm.is_valid():
#1.获取数据,cleaned_data 就是读取表单返回的值,返回类型为字典dict型
data = registerForm.cleaned_data
| username = data.get('username')
nickname = data.get('nickname')
password = data.get('password')
#picture=data.get('picture')如果这样获取的是图片名称
picture = request.FILES.get('picture')#获取的是图片对象
time_temp = time.time()#获取当前时间戳
#2.保存图片
path =... | identifier_name | |
views.py | def index(request):
# 1.获取当前登录时间
times = datetime.datetime.now()
# 2. 获取头像
seller_id = request.session.get('seller_id')
seller_obj = models.Seller.objects.get(id=seller_id)
# models.Seller.objects.get(name=request.session.get('username'))这种方法获取头像也行,要不就整个id出来,即116行
# print(seller_obj.picture.... | identifier_body | ||
views.py | def index(request):
# 1.获取当前登录时间
times = datetime.datetime.now()
# 2. 获取头像
seller_id = request.session.get('seller_id')
seller_obj = models.Seller.objects.get(id=seller_id)
# models.Seller.objects.get(name=request.session.get('username'))这种方法获取头像也行,要不就整个id出来,即116行
# print(seller_obj.picture.... | conditional_block | ||
pan2mqtt.py | False
self.mqtt_subcriptions = {}
self.downlink_topics = {}
self.uplink_topics = {}
self.pan = Factory(self.config['pan']['driver_class'])
if not self.pan:
self.__log(logging.ERROR, "Can't instant pan driver")
sys.exit(2)
self.pan.logger = logger... |
print "topic list:" + str_topic_holder
self.mqtt_client.publish(dst_topic, str_topic_holder, 2)
###
def on_mqtt_connect (self, client, userdata, flags, rc):
if rc == 0:
self.__log(logging.INFO, "Connected to MQTT brok... | for mac,mac_obj in self.config['pan']['nodes'].items():
for topic,topic_content in mac_obj.items():
topic = topic.format(client_id=self.client_id)
if topic_content['dir'] == "uplink" and topic_content['type'] != "listening":
str_topic_holde... | conditional_block |
pan2mqtt.py |
self.mqtt_subcriptions = {}
self.downlink_topics = {}
self.uplink_topics = {}
self.pan = Factory(self.config['pan']['driver_class'])
if not self.pan:
self.__log(logging.ERROR, "Can't instant pan driver")
sys.exit(2)
self.pan.logger = logger
... | (self):
self.downlink_topics = {}
self.uplink_topics = {}
if self.config['pan']['nodes']:
for mac,mac_obj in self.config['pan']['nodes'].items():
for topic,topic_content in mac_obj.items():
topic = topic.format(client_id=self.client_id)
... | __parse_nodes | identifier_name |
pan2mqtt.py |
self.mqtt_subcriptions = {}
self.downlink_topics = {}
self.uplink_topics = {}
self.pan = Factory(self.config['pan']['driver_class'])
if not self.pan:
self.__log(logging.ERROR, "Can't instant pan driver")
sys.exit(2)
self.pan.logger = logger
... |
def on_mqtt_log (self, client, userdata, level, buf):
self.__log(logging.DEBUG, buf)
def on_message_from_pan (self, mac, key, value, type):
self.__log(logging.INFO, "Received message from PAN: %s, %s:%s" % (mac, key, value))
#walk over plugins and determin whether to drop
'''... | topic = self.mqtt_subcriptions.get(mid, "Unknown")
self.__log(logging.INFO, "Sub to topic %s confirmed"%topic) | identifier_body |
pan2mqtt.py | False
self.mqtt_subcriptions = {}
self.downlink_topics = {}
self.uplink_topics = {}
self.pan = Factory(self.config['pan']['driver_class'])
if not self.pan:
self.__log(logging.ERROR, "Can't instant pan driver")
sys.exit(2)
self.pan.logger = logger... | self.__log(logging.INFO, "Sub to topic %s confirmed"%topic)
def on_mqtt_log (self, client, userdata, level, buf):
self.__log(logging.DEBUG, buf)
def on_message_from_pan (self, mac, key, value, type):
self.__log(logging.INFO, "Received message from PAN: %s, %s:%s" % (mac, key, value))
... | random_line_split | |
install_dotfiles.py | , self.notifier_send_channel:
async for chunk in self.process.stdout:
# print(f"seen chunk: '{chunk!r}'", flush=True) # debug
self.stdout += chunk
await self.printer_send_channel.send(chunk)
# send notification
# if it's... | get_pip_file = self.CACHE_DIR / "get_pip.py"
get_pip_file.touch()
with get_pip_file.open(mode="wb") as file:
with urlopen("https://bootstrap.pypa.io/get-pip.py") as request:
while request.peek(1):
file.write(request.read(8192 | # >> ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate
self.shell("iwr -useb https://bootstrap.pypa.io")
# https://pip.pypa.io/en/stable/installation/#get-pip-py
| random_line_split |
install_dotfiles.py | ("missing process; was this called inside a with statement?")
assert self.process.stdin is not None, "process must be opened with stdin=PIPE"
# NOTE: This could be improved to show which responses were sent, and which
# weren't
self.response_sent = False
async with self.... | if not self._PIP_INSTALLED:
self.bootstrap_pip()
# NOTE: pip forces the --user flag on Microsoft Store Pythons:
# https://stackoverflow.com/q/63783587
self.cmd([self.PYTHON_EXECUTABLE, "-m", "pip", *args, "--no-user"]) | identifier_body | |
install_dotfiles.py | , self.notifier_send_channel:
async for chunk in self.process.stdout:
# print(f"seen chunk: '{chunk!r}'", flush=True) # debug
self.stdout += chunk
await self.printer_send_channel.send(chunk)
# send notification
# if it's... |
assert venv_modules.is_dir(), f"missing directory '{venv_modules}'"
self.PYTHON_EXECUTABLE = str(venv_python)
sys.path.insert(0, str(venv_modules))
# Install trio
self.pip(["install", "trio"])
import trio as trio_module # isort:skip
global trio
... | raise Exception(
f"could not find a virtual environment python at '{venv_python}'"
) | conditional_block |
install_dotfiles.py | (name: str) -> Optional[str]:
if not WINDOWS:
raise NotImplementedError(
"can only update environment variables on Windows for now"
)
with winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER) as root:
with winreg.OpenKey(root, "Environment", 0, winreg.KEY_ALL_ACCESS... | win_get_user_env | identifier_name | |
64112.user.js |
}
// if on a search page
if (/[?#](.*&)?q=/i.test(location.href)) {
var queryString = location.href.substring(location.href.indexOf('?'));
var origQueryString = queryString;
// change the query string if necessary
// if hl (interface language) is specified, change it because it is only specified from the ... | {
document.removeEventListener('DOMNodeInserted', checkURL, true); // we need to remove the event listener or we might cause an infinite loop
var newURL = location.href.replace(reg, '$1search?$5');
newURL = newURL.replace(/&fp=[^&]*/i, ''); // remove fp also, otherwise the new page will be blank
... | conditional_block | |
64112.user.js |
// if on a search page
if (/[?#](.*&)?q=/i.test(location.href)) {
var queryString = location.href.substring(location.href.indexOf('?'));
var origQueryString = queryString;
// change the query string if necessary
// if hl (interface language) is specified, change it because it is only specified from the pr... | {
if (reg.test(location.href)) {
document.removeEventListener('DOMNodeInserted', checkURL, true); // we need to remove the event listener or we might cause an infinite loop
var newURL = location.href.replace(reg, '$1search?$5');
newURL = newURL.replace(/&fp=[^&]*/i, ''); // remove fp also, otherwis... | identifier_body | |
64112.user.js | ) and add it back with the right value
queryString = queryString.replace(/(.*?)[?&]hl=[^&]*(.*)/,'$1$2');
queryString += '&hl=' + interfaceLanguage;
}
}
if (searchLanguage) {
var lrSetRight = new RegExp('[?&]lr='+searchLanguage);
if (!lrSetRight.test(queryString)) { // include ... | "zu": "Zulu"
}
pageBody += '<p><label>Display Google tips and messages in: <select id="GPWOC_hl">';
for (var i in interfaceLanguages) {
pageBody += '<option value="' + i + '"' + ((interfaceLanguage==i)?' selected="selected"':'') + '>' + interfaceLanguages[i] + '</option>';
}
pageBody += '</sele... | "xh": "Xhosa",
"yi": "Yiddish",
"yo": "Yoruba", | random_line_split |
64112.user.js | () {
if (reg.test(location.href)) {
document.removeEventListener('DOMNodeInserted', checkURL, true); // we need to remove the event listener or we might cause an infinite loop
var newURL = location.href.replace(reg, '$1search?$5');
newURL = newURL.replace(/&fp=[^&]*/i, ''); // remove fp also, other... | checkURL | identifier_name | |
api_op_Search.go | iddleware.AddRecordResponseTiming(stack); err != nil {
return err
}
if err = addClientUserAgent(stack, options); err != nil {
return err
}
if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil {
return err
}
if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil {
retur... | {
return stack.Serialize.Insert(&opSearchResolveEndpointMiddleware{
EndpointResolver: options.EndpointResolverV2,
BuiltInResolver: &builtInResolver{
Region: options.Region,
UseFIPS: options.EndpointOptions.UseFIPSEndpoint,
Endpoint: options.BaseEndpoint,
},
}, "ResolveEndpoint", middleware.After)
} | identifier_body | |
api_op_Search.go | )
out.ResultMetadata = metadata
return out, nil
}
type SearchInput struct {
// A string that includes keywords and filters that specify the resources that you
// want to include in the results. For the complete syntax supported by the
// QueryString parameter, see Search query syntax reference for Resource Explo... | (ctx context.Context, optFns ...func(*Options)) (*SearchOutput, error) {
if !p.HasMorePages() {
return nil, fmt.Errorf("no more pages available")
}
params := *p.params
params.NextToken = p.nextToken
var limit *int32
if p.options.Limit > 0 {
limit = &p.options.Limit
}
params.MaxResults = limit
result, er... | NextPage | identifier_name |
api_op_Search.go | )
out.ResultMetadata = metadata
return out, nil
}
type SearchInput struct {
// A string that includes keywords and filters that specify the resources that you
// want to include in the results. For the complete syntax supported by the
// QueryString parameter, see Search query syntax reference for Resource Explo... |
if err = addSetLoggerMiddleware(stack, options); err != nil {
return err
}
if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil {
return err
}
if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil {
return err
}
if err = addResolveEndpointMiddleware(stack, options); er... | {
return err
} | conditional_block |
api_op_Search.go | smiddleware.AddRecordResponseTiming(stack); err != nil {
return err
}
if err = addClientUserAgent(stack, options); err != nil {
return err
}
if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil {
return err
}
if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil {
ret... | UseFIPS: options.EndpointOptions.UseFIPSEndpoint,
Endpoint: options.BaseEndpoint,
},
}, "ResolveEndpoint", middleware.After)
} | random_line_split | |
imap.go | timeout=%d", waitTime)
if waitTime > 0 {
waitUntil := time.Now().Add(time.Duration(waitTime) * time.Millisecond)
imap.tlsConn.SetReadDeadline(waitUntil)
}
for i := 0; ; i++ {
ok := imap.scanner.Scan()
if ok {
break
} else {
err := imap.scanner.Err()
if err == nil {
return "", errors.New("EOF r... | cancel | identifier_name | |
imap.go | handleGreeting() error {
imap.Debug("Handle Greeting")
response, err := imap.getServerResponse(uint64(replyTimeout / time.Millisecond))
if err == nil {
imap.Info("Connected|host=%s|tag=%s", imap.url.Host, imap.tag.id)
if imap.isOKResponse(response) {
imap.Info("Greeting from server: %s", response)
return ... | imap.Info("Saving starting EXISTS count|IMAPEXISTSCount=%d||msgCode=IMAP_STARTING_EXISTS_COUNT", count)
imap.pi.IMAPEXISTSCount = count
} else if token == IMAP_UIDNEXT {
imap.Info("Setting starting IMAPUIDNEXT|IMAPUIDNEXT=%d", count)
imap.pi.IMAPUIDNEXT = count
}
case "STATUS":
imap.Debug("Processing... | count, token := imap.parseEXAMINEResponse(response)
if token == IMAP_EXISTS { | random_line_split |
imap.go | []string
var err error
for _, commandLine := range commandLines {
err := imap.sendIMAPCommand(commandLine)
if err != nil {
imap.Warning("%s", err)
return nil, err
}
if imap.cancelled == true {
imap.Info("IMAP Command. Request cancelled. Exiting|msgCode=IMAP_COMMAND_CANCELLED")
err = fmt.Errorf("R... | {
imap.Info("IMAP Request cancelled. Exiting|msgCode=IMAP_REQ_CANCELLED")
return
} | conditional_block | |
imap.go |
func (t *cmdTag) String() string {
return fmt.Sprintf("%s%d", t.id, t.seq)
}
func (imap *IMAPClient) setupScanner() {
imap.scanner = bufio.NewScanner(imap.tlsConn)
imap.scanner.Split(bufio.ScanLines)
}
func (imap *IMAPClient) isContinueResponse(response string) bool {
if len(response) > 0 && response[0] == '+' ... | {
t.seq++
return string(strconv.AppendUint(t.id, t.seq, 10))
} | identifier_body | |
singer.go | () {
base.RegisterDriver(base.SingerType, NewSinger)
base.RegisterTestConnectionFunc(base.SingerType, TestSinger)
}
//NewSinger returns Singer driver and
//1. writes json files (config, catalog, properties, state) if string/raw json was provided
//2. runs discover and collects catalog.json
//2. creates venv
//3. in ... | init | identifier_name | |
singer.go | return fmt.Errorf("Error updating singer tap [%s]: %v", s.tap, err)
}
//override initial state with existing one and put it to a file
var statePath string
var err error
if state != "" {
statePath, err = parseJSONAsFile(path.Join(singer.Instance.VenvDir, s.sourceID, s.tap, stateFileName), state)
if err != nil... | {
catalogBytes, err := ioutil.ReadFile(catalogPath)
if err != nil {
return nil, fmt.Errorf("Error reading catalog file: %v", err)
}
catalog := &SingerCatalog{}
err = json.Unmarshal(catalogBytes, catalog)
if err != nil {
return nil, err
}
streamTableNamesMapping := map[string]string{}
for _, stream := ra... | identifier_body | |
singer.go | )
if err != nil {
return nil, fmt.Errorf("Error parsing singer config [%v]: %v", config.Config, err)
}
//parse singer catalog as file path
catalogPath, err := parseJSONAsFile(path.Join(pathToConfigs, catalogFileName), config.Catalog)
if err != nil {
return nil, fmt.Errorf("Error parsing singer catalog [%v]: %... | s.catalogPath = catalogPath
s.propertiesPath = propertiesPath
s.catalogDiscovered.Store(true)
return
}
}
//GetTableNamePrefix returns stream table name prefix or sourceID_
func (s *Singer) GetTableNamePrefix() string {
//put as prefix + stream if prefix exist
if s.tableNamePrefix != "" {
return s.tableNa... | continue
}
| random_line_split |
singer.go | if err != nil {
return nil, fmt.Errorf("Error parsing singer config [%v]: %v", config.Config, err)
}
//parse singer catalog as file path
catalogPath, err := parseJSONAsFile(path.Join(pathToConfigs, catalogFileName), config.Catalog)
if err != nil {
return nil, fmt.Errorf("Error parsing singer catalog [%v]: %v"... |
if s.catalogDiscovered.Load() {
break
}
if !singer.Instance.IsTapReady(s.tap) {
time.Sleep(time.Second)
continue
}
catalogPath, propertiesPath, err := doDiscover(s.sourceID, s.tap, s.pathToConfigs, s.configPath)
if err != nil {
logging.Errorf("[%s] Error configuring Singer: %v", s.sourceID, ... | {
break
} | conditional_block |
mapper.rs | <'_>) -> Result<()> {
match Mapper::args(Some(GameModeOption::Osu), args, Some("sotarks")) {
Ok(args) => mapper(ctx, msg.into(), args).await,
Err(content) => {
msg.error(&ctx, content).await?;
Ok(())
}
}
}
async fn slash_mapper(ctx: Arc<Context>, mut command: In... | .count_miss
.cmp(&a.score.statistics.count_miss)
.then_with(|| {
let hits_a = a.score.total_hits(); | random_line_split | |
mapper.rs | `Condensed` shows 10 scores, `Detailed` shows 5, and `Single` shows 1.\n\
The default can be set with the `/config` command."
)]
size: Option<ListSize>,
}
impl<'m> Mapper<'m> {
fn args(
mode: Option<GameModeOption>,
mut args: Args<'m>,
mapper: Option<&'static str>,
... | (ctx: Arc<Context>, msg: &Message, args: Args<'_>) -> Result<()> {
match Mapper::args(Some(GameModeOption::Taiko), args, None) {
Ok(args) => mapper(ctx, msg.into(), args).await,
Err(content) => {
msg.error(&ctx, content).await?;
Ok(())
}
}
}
#[command]
#[desc("H... | prefix_mappertaiko | identifier_name |
mapper.rs | `Condensed` shows 10 scores, `Detailed` shows 5, and `Single` shows 1.\n\
The default can be set with the `/config` command."
)]
size: Option<ListSize>,
}
impl<'m> Mapper<'m> {
fn args(
mode: Option<GameModeOption>,
mut args: Args<'m>,
mapper: Option<&'static str>,
... | None => match config.osu.take() {
Some(user_id) => UserId::Id(user_id),
None => return require_link(&ctx, &orig).await,
},
};
let mapper = args.mapper.cow_to_ascii_lowercase();
let mapper_args = UserArgs::username(&ctx, mapper.as_ref()).await.mode(mode);
let mapp... | {
let msg_owner = orig.user_id()?;
let mut config = match ctx.user_config().with_osu_id(msg_owner).await {
Ok(config) => config,
Err(err) => {
let _ = orig.error(&ctx, GENERAL_ISSUE).await;
return Err(err);
}
};
let mode = args
.mode
.ma... | identifier_body |
linked-data-provider.service.ts | ";
import * as pointer from 'json-pointer';
import * as debuglib from 'debug';
var debug = debuglib('schema-ui:linked-data-provider');
/**
* Class that helps with resolving linked field data.
*
* This class is used by some fields.
*/
@Injectable()
export class LinkedDataProvider {
/**
* Cached promise so... | return pointer.get(item, this.field.meta.field.data['pointer'] || '/');
}
catch (e) {
debug(`[warn] unable to get the data for pointer "${this.field.meta.field.data['pointer']}"`);
... | .then(item => {
try { | random_line_split |
linked-data-provider.service.ts | ";
import * as pointer from 'json-pointer';
import * as debuglib from 'debug';
var debug = debuglib('schema-ui:linked-data-provider');
/**
* Class that helps with resolving linked field data.
*
* This class is used by some fields.
*/
@Injectable()
export class LinkedDataProvider {
/**
* Cached promise so... |
if (a.order > b.order) {
return 1;
}
return -1;
}));
}
/**
* Chooses between the ambient context and the one given, and returns the correct one (eventually).
*/
private chooseAppropriateContext(context?: any): Promis... | {
return String(a.name).localeCompare(String(b.name));
} | conditional_block |
linked-data-provider.service.ts | ";
import * as pointer from 'json-pointer';
import * as debuglib from 'debug';
var debug = debuglib('schema-ui:linked-data-provider');
/**
* Class that helps with resolving linked field data.
*
* This class is used by some fields.
*/
@Injectable()
export class LinkedDataProvider {
/**
* Cached promise so... |
/**
* Convert the given list of simplified values to a list of the actual linked objects.
*
* @param items The simplified linked resource items.
*/
public getLinkedDataFromSimplifiedLinkedData(items: SimplifiedLinkedResource[]): Promise<any | IdentityValue[]> {
if (typeof this.fiel... | {
return this.chooseAppropriateContext(context).then(ctx =>
this.mapMultipleChoice(items, ctx, forceReload, includeOriginal));
} | identifier_body |
linked-data-provider.service.ts | ";
import * as pointer from 'json-pointer';
import * as debuglib from 'debug';
var debug = debuglib('schema-ui:linked-data-provider');
/**
* Class that helps with resolving linked field data.
*
* This class is used by some fields.
*/
@Injectable()
export class LinkedDataProvider {
/**
* Cached promise so... | ield: ExtendedFieldDescriptor, item: any): IdentityValue {
if (field.field.data == null || field.field.data.parent == | tParentValue(f | identifier_name |
dp.rs | >>) -> i32 {
let row = grid.len();
let col = grid[0].len();
let mut cost = grid.clone();
for r in 0..row {
for c in 0..col {
if r == 0 && c == 0 {
cost[r][c] = grid[r][c];
} else if r == 0 {
cost[r][c] = grid[r][c] + cost[r][c-1];
... | dp[i][j] = dp[i-1][j] + dp[i][j-1];
}
} else {
// 遇到障碍了,但一开始我们就是初始化为0的,所以这里其实可以不写
dp[i][j] = 0;
}
}
}
return dp[row-1][col-1];
}
// https://leetcode-cn.com/problems/re-space-lcci/
pub fn respace(dictionary: Vec<String>,... | identifier_body | |
dp.rs | [n][2]);
}
pub fn max_profit_once(prices: Vec<i32>) -> i32 {
// suffix 0 means no trade (buy or sell) happen
// 1 means it happend
// let mut s_keep_0 = std::i32::MIN; // you could not keep any stock on the very first day
let mut s_empty_0 = 0;
let mut s_keep_1 = std::i32::MIN;
let mut s_empt... | st[r-1][c];
} else {
cost[r][c] = grid[r][c] + min(cost[r-1][c], cost[r][c-1]);
}
}
}
return cost[row-1][col-1];
}
// https://leetcode-cn.com/problems/generate-parentheses/solution/
pub fn generate_parenthesis(n: i32) -> Vec<String> {
if n == 0 {
ret... | d[r][c] + co | identifier_name |
dp.rs | vec![String::from("")];
for i in 1..=n {
println!("Round {}", i);
let mut cur = vec![];
for j in 0..i {
let left = &dp[j as usize];
let right = &dp[(i-j-1) as usize];
for l in left {
for r in right {
let tmp = format!("... | ("i, j = {}, {}", i, j);
dp[j] = dp[j].min(dp[j | conditional_block | |
dp.rs | let mut ans = nums[0];
for i in 1..nums.len() {
if sum > 0 {
// add positive sum means larger
sum += nums[i];
} else {
// start from new one means larger
sum = nums[i];
}
// ans always store the largest sum
ans = std::cmp::... | // 最大子序各,好像看不出什么动态规则的意味,反而像滑动窗口
pub fn max_sub_array(nums: Vec<i32>) -> i32 {
let mut sum = nums[0]; | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.