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 |
|---|---|---|---|---|
tags.rs |
Unknown(String)
}
/// Supported canvas image formats.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ImageFormat {
Png,
Jpg,
}
/// Element in the HTML DOM that can be accessed by Rust interface.
pub trait Element: Debug {
/// Tag name of the element.
fn tag_name(&self) -> TagName;
//... | random_line_split | ||
tags.rs | attr;\
window.external.invoke(JSON.stringify({{\
incmd: 'attribute',\
request: {},\
value: attr\
}}));\
", self.id(), name, id);
let receiver = request.run(js);
let attr = receiver.recv().unwrap();
if let ResponseV... | try_from_node | identifier_name | |
destination.rs | the i-th buffer.
let mut buffer_column_index = vec![vec![]; nbuffers];
let mut column_buffer_index_cid: Vec<_> = column_buffer_index.iter().enumerate().collect();
column_buffer_index_cid.sort_by_key(|(_, blk)| *blk);
for (cid, &(blkno, _)) in column_buffer_index_cid {
buffe... | // blknos[i] identifies the block from self.blocks that contains this column.
// blklocs[i] identifies the column of interest within
// self.blocks[self.blknos[i]] | random_line_split | |
destination.rs | ,
}
}
pub fn result(self) -> Option<&'a PyAny> {
self.dataframe
}
}
impl<'a> Destination for PandasDestination<'a> {
const DATA_ORDERS: &'static [DataOrder] = &[DataOrder::RowMajor];
type TypeSystem = PandasTypeSystem;
type Partition<'b> = PandasPartitionDestination<'b>;
#... | (&self) -> &[PandasTypeSystem] {
static EMPTY_SCHEMA: Vec<PandasTypeSystem> = vec![];
self.schema.as_ref().unwrap_or(EMPTY_SCHEMA.as_ref())
}
}
pub struct PandasPartitionDestination<'a> {
nrows: usize,
columns: Vec<Box<dyn PandasColumnObject + 'a>>,
schema: &'a [PandasTypeSystem],
s... | schema | identifier_name |
destination.rs | ,
}
}
pub fn result(self) -> Option<&'a PyAny> {
self.dataframe
}
}
impl<'a> Destination for PandasDestination<'a> {
const DATA_ORDERS: &'static [DataOrder] = &[DataOrder::RowMajor];
type TypeSystem = PandasTypeSystem;
type Partition<'b> = PandasPartitionDestination<'b>;
#... |
}
pub struct PandasPartitionDestination<'a> {
nrows: usize,
columns: Vec<Box<dyn PandasColumnObject + 'a>>,
schema: &'a [PandasTypeSystem],
seq: usize,
}
impl<'a> PandasPartitionDestination<'a> {
fn new(
nrows: usize,
columns: Vec<Box<dyn PandasColumnObject + 'a>>,
schema:... | {
static EMPTY_SCHEMA: Vec<PandasTypeSystem> = vec![];
self.schema.as_ref().unwrap_or(EMPTY_SCHEMA.as_ref())
} | identifier_body |
towrap.go | 64(0)
return CRConfigHistoryThreadsafe{hist: &hist, m: &sync.RWMutex{}, limit: &limit, length: &length, pos: &pos}
}
// Add adds the given stat to the history. Does not add new additions with the
// same remote address and CRConfig Date as the previous.
func (h CRConfigHistoryThreadsafe) Add(i *CRConfigStat) {
h.m.L... |
// CRConfigValid checks if the passed tc.CRConfig structure is valid, and
// ensures that it is from the same CDN as the last CRConfig Snapshot, as well
// as that it is newer than the last CRConfig Snapshot.
func (s *TrafficOpsSessionThreadsafe) CRConfigValid(crc *tc.CRConfig, cdn string) error {
if crc == nil {
... | {
return s.crConfigHist.Get()
} | identifier_body |
towrap.go | properly initialized with non-nil sessions.
func (s TrafficOpsSessionThreadsafe) Initialized() bool {
return s.session != nil && *s.session != nil && s.legacySession != nil && *s.legacySession != nil
}
// Update updates the TrafficOpsSessionThreadsafe's connection information with
// the provided information. It's s... |
if crConfig == nil {
if err = json.Unmarshal(configBytes, crConfig); err != nil {
err = errors.New("invalid JSON: " + err.Error())
hist.Err = err | random_line_split | |
towrap.go | 64(0)
return CRConfigHistoryThreadsafe{hist: &hist, m: &sync.RWMutex{}, limit: &limit, length: &length, pos: &pos}
}
// Add adds the given stat to the history. Does not add new additions with the
// same remote address and CRConfig Date as the previous.
func (h CRConfigHistoryThreadsafe) Add(i *CRConfigStat) {
h.m.L... |
}
(*h.hist)[*h.pos] = *i
*h.pos = (*h.pos + 1) % *h.limit
if *h.length < *h.limit {
*h.length++
}
}
// Get retrieves the stored history of CRConfigStat entries.
func (h CRConfigHistoryThreadsafe) Get() []CRConfigStat {
h.m.RLock()
defer h.m.RUnlock()
if *h.length < *h.limit {
return CopyCRConfigStat((*h.... | {
return
} | conditional_block |
towrap.go | 64(0)
return CRConfigHistoryThreadsafe{hist: &hist, m: &sync.RWMutex{}, limit: &limit, length: &length, pos: &pos}
}
// Add adds the given stat to the history. Does not add new additions with the
// same remote address and CRConfig Date as the previous.
func (h CRConfigHistoryThreadsafe) Add(i *CRConfigStat) {
h.m.L... | (crc *tc.CRConfig, cdn string) error {
if crc == nil {
return errors.New("CRConfig is nil")
}
if crc.Stats.CDNName == nil {
return errors.New("CRConfig.Stats.CDN missing")
}
if crc.Stats.DateUnixSeconds == nil {
return errors.New("CRConfig.Stats.Date missing")
}
// Note this intentionally takes intended C... | CRConfigValid | identifier_name |
main.rs | Vec::new();
//Checks if previous char was a | operator.
//If so, save the current character as a transition or cycle character
//Also fixes any previous transition state
if previous_char == '|' {
for (n, a) in dfa.alphabet.iter().enumerate() {
if *a == c {
dfa.transitions[0][n] = next_sta... | self) { | identifier_name | |
main.rs | transitions
transitions: Vec<usize>
}
struct Transitions {
chars: char,
state: usize
}
fn main() {
//Get and validate the RegEx on the command line
let regex = get_regex(std::env::args());
let dfa = DFA::new_from_regex(®ex);
//Create the dfa structure based on in RegEx entered from the command line
... | //At the end, add 2 to current state to get back, and set previous_char as *
else if c == '*' {
dfa.transitions.remove(dfa.transitions.len()-1);
let mut pushed_forward = false;
next_state -= 2;
current_state -= 2;
for a in dfa.alphabet.iter() {
if a == &previous_char {
next_state ... | // Potential fix is similar to + operator with iterating over transitions instead of just checking index 0. | random_line_split |
main.rs | transitions
transitions: Vec<usize>
}
struct Transitions {
chars: char,
state: usize
}
fn main() |
// *********************************************************************
/// Return the RegEx passed as the first parameter
fn get_regex(args: std::env::Args) -> String {
// Get the arguments as a vector
let args: Vec<String> = args.collect();
// Make sure only one argument was passed
if args.len() ... | {
//Get and validate the RegEx on the command line
let regex = get_regex(std::env::args());
let dfa = DFA::new_from_regex(®ex);
//Create the dfa structure based on in RegEx entered from the command line
let state_graph = StateGraph::new_from_dfa(&dfa);
//eprintln!("{:?}", state_graph);
state_graph.... | identifier_body |
cblmg_cs_supplierCoachGeocoder.js | 0) {
nlapiSelectLineItem('addressbook', shipLine);
oShipAdrText = nlapiGetCurrentLineItemValue('addressbook', 'addrtext');
//oShipAdrText = nlapiGetLineItemValue('addressbook', 'addrtext', shipLine)?nlapiGetLineItemValue('addressbook', 'addrtext', shipLine):'';
}
//Changing it so that we ONLY execute drawGoo... |
} else {
geoAddressText += nlapiGetFieldValue(document.getElementById(geoflds[g]).value)?nlapiGetFieldValue(document.getElementById(geoflds[g]).value):''+' ';
}
} else {
//2014v2 Update - Must use nlapiGetCurrentLineItemValue
nlapiSelectLineItem('addressbook', shipLine);
... | {
stateVal = strGlobalReplace(stateVal, 'CA - ', '');
stateVal = strGlobalReplace(stateVal, 'US - ', '');
geoAddressText += stateVal+' ';
} | conditional_block |
cblmg_cs_supplierCoachGeocoder.js | 0) {
nlapiSelectLineItem('addressbook', shipLine);
oShipAdrText = nlapiGetCurrentLineItemValue('addressbook', 'addrtext');
//oShipAdrText = nlapiGetLineItemValue('addressbook', 'addrtext', shipLine)?nlapiGetLineItemValue('addressbook', 'addrtext', shipLine):'';
}
//Changing it so that we ONLY execute drawGoo... | (type, name, linenum) {
if (!canGeoCode) {
return;
}
//If both Lat/Lng values are set, display the Google Map map_canvas
//ONLY Redraw IF Both Lat/Lng values are provided
if ((name=='custentity_cbl_shipadr_lat' || name=='custentity_cbl_shipadr_lng') && nlapiGetFieldValue('custentity_cbl_shipadr_lat') && nlap... | supplierFldChanged | identifier_name |
cblmg_cs_supplierCoachGeocoder.js | > 0) {
nlapiSelectLineItem('addressbook', shipLine);
oShipAdrText = nlapiGetCurrentLineItemValue('addressbook', 'addrtext');
//oShipAdrText = nlapiGetLineItemValue('addressbook', 'addrtext', shipLine)?nlapiGetLineItemValue('addressbook', 'addrtext', shipLine):'';
}
//Changing it so that we ONLY execute drawG... |
window.open(radiusSlUrl,'Radius_Search','width=1200,height=700,resizable=yes,scrollbars=yes');
}
function setValueFromRadiusLookup(_id) {
nlapiSetFieldValue('custentity_bo_coach', _id, true, true);
}
function drawGoogleMapByGeoCode() {
//Make sure map_canvas div element is present
if (!document.getElementBy... | '&bookdatetime='+encodeURIComponent(bookingDate+' '+bookingTime)+'&course='+encodeURIComponent(bookingCourse)+
'&item='+encodeURIComponent(bookingItem)+'&client='+bookingClientText+'&selectedcoachtext='+selectedCoachText+
'&entityid='+nlapiGetFieldValue('entityid')+'&bookid='+nlapiGetRecordId()+'&b... | random_line_split |
cblmg_cs_supplierCoachGeocoder.js | 0) {
nlapiSelectLineItem('addressbook', shipLine);
oShipAdrText = nlapiGetCurrentLineItemValue('addressbook', 'addrtext');
//oShipAdrText = nlapiGetLineItemValue('addressbook', 'addrtext', shipLine)?nlapiGetLineItemValue('addressbook', 'addrtext', shipLine):'';
}
//Changing it so that we ONLY execute drawGoo... |
/**
* The recordType (internal id) corresponds to the "Applied To" record in your script deployment.
* @appliedtorecord recordType
*
* @returns {Boolean} True to continue save, false to abort save
*/
function supplierSaveRecord(){
//Attempt to geocode ONLY on User Interface
if (canGeoCode && nlapiGetConte... | {
if (canGeoCode && type == 'addressbook' && nlapiGetCurrentLineItemValue(type, 'defaultshipping')=='T') {
var nShipAdrText = nlapiGetCurrentLineItemValue('addressbook', 'addrtext')?nlapiGetCurrentLineItemValue('addressbook', 'addrtext'):'';
//alert(oShipAdrText +' // '+nShipAdrText);
if (oShipAdrText != nShi... | identifier_body |
i2c.rs | = if speed <= Frequency::KHz(100) {
clocks.apb1.mhz() + 1
} else {
((clocks.apb.mhz() * 300) / 1000) + 1
};
// Configure correct rise times
new.write_bits(8, 0, trise, 6);
// I2C clock control calculation
// If in slow mode
if speed <= Frequency::KHz(100) {
let ccr = match clocks.apb.hz() / (s... | address_mode | identifier_name | |
i2c.rs | back.
fn read(&mut self, addr: u8, buffer: &mut [u8]) -> Result<(), I2CError> {
let last = buffer.len() - 1;
// Send start condition and ACK bit
self.start()
.ack();
// Wait until START condition is generated
while !self.is_set(5, 0) {}
// Wait until all devices are listening to us (bus is free)
whi... | {
(self.block[6].read() >> 8) & 0b1111_1111
} | identifier_body | |
i2c.rs | 2CError::Other),
};
let new = I2c {
block: &mut *(address as *mut _),
pins,
};
let (sda, scl) = pins;
// TODO : Change to each board
sda.altfn(4)
.speed(HIGH);
scl.altfn(4)
.speed(HIGH);
rcc.peripheral_state(true, i2cid);
rcc.reset_peripheral(i2cid);
// TODO set up RCC clocks
// ... |
// Clear condition by reading SR2
let _ = self.block[6].read();
// Store bytes
for i in 0..last {
buffer[i] = self.recv_byte()?;
}
self.nack()
.stop();
// Read last byte
buffer[last] = self.recv_byte()?;
Ok(())
}
}
impl Write for I2c {
type Error = I2CError;
/// Send a buffer of bytes
... | while !self.is_set(5, 1) {} | random_line_split |
bot.go | Path {
path = append(path, game.GetIndex(node.X, node.Y))
}
return path, nil
}
func GetBestMove(game *gioframework.Game) (bestFrom int, bestTo int) {
defer func() {
if r := recover(); r != nil {
log.Printf("ERROR, GetBestMove recovered from panic: %v", r)
fmt.Println(errors.Wrap(r, 2).ErrorStack())
bes... | {
return math.Min(math.Max(val, min), max)
} | identifier_body | |
bot.go | ies)
game.Attack(path[i], path[i+1], false)
}
}
log.Printf("Replay available at: http://bot.generals.io/replays/%v", game.ReplayID)
time.Sleep(10*time.Second)
}
}
func setupLogging() {
logDir := "log"
_ = os.Mkdir(logDir, os.ModePerm)
rand.Seed(time.Now().UTC().UnixNano())
logFilename := path.Join(l... | (b bool) int {
if b {
return 1
}
return 0
}
func Btof(b bool) float64 {
if b {
return 1.
}
return 0.
}
func getHeuristicPathDistance(game *gioframework.Game, from, to int) float64 {
/* Would have preferred to use A* to get actual path distance, but that's
prohibitvely expensive. (I need to calculate th... | Btoi | identifier_name |
bot.go | ies)
game.Attack(path[i], path[i+1], false)
}
}
log.Printf("Replay available at: http://bot.generals.io/replays/%v", game.ReplayID)
time.Sleep(10*time.Second)
}
}
func setupLogging() {
logDir := "log"
_ = os.Mkdir(logDir, os.ModePerm)
rand.Seed(time.Now().UTC().UnixNano())
logFilename := path.Join(l... | scores["outnumbered penalty"] = -0.2 * Btof(outnumber < 2)
scores["general threat score"] = (0.25 * math.Pow(distFromGen, -1.0)) *
Truncate(float64(toTile.Armies)/10, 0., 1.0) * Btof(isEnemy)
scores["dist penalty"] = Truncate(-0.5*dist/30, -0.3, 0)
scores["dist gt army penalty"] = -0.2 * Btof(fromTile.A | scores["outnumber score"] = Truncate(outnumber/200, 0., 0.25) * Btof(isEnemy) | random_line_split |
bot.go | on route to
// somewhere else. Note: if it is the final destination, it'll be
// changed
not_my_city := tile.Type == gioframework.City && tile.Faction != game.PlayerIndex
map_data[row][col] = Btoi(!game.Walkable(i) || not_my_city)
}
}
map_data[game.GetRow(from)][game.GetCol(from)] = pathfinding.START
... | {
// This means we're playing 1v1 or FFA
return tile.Faction != game.PlayerIndex && tile.Faction >= 0
} | conditional_block | |
data_window.go | // CurrentTiflashTableScanWithFastScanCount count the number of tiflash table scan and tiflash partition table scan which use fastscan
CurrentTiflashTableScanWithFastScanCount atomic.Uint64
)
const (
// WindowSize determines how long some data is aggregated by.
WindowSize = 1 * time.Hour
// SubWindowSize determin... | if i == 0 {
startWindow = thisWindow
} else {
startWindow = *rotatedSubWindows[i-1]
} | random_line_split | |
data_window.go | HitRatioGTE0Count atomic.Uint64
// CurrentCoprCacheHitRatioGTE1Count is CurrentCoprCacheHitRatioGTE1Count
CurrentCoprCacheHitRatioGTE1Count atomic.Uint64
// CurrentCoprCacheHitRatioGTE10Count is CurrentCoprCacheHitRatioGTE10Count
CurrentCoprCacheHitRatioGTE10Count atomic.Uint64
// CurrentCoprCacheHitRatioGTE20Coun... |
return result, err
}
func analysisSQLUsage(promResult pmodel.Value, sqlResult *sqlUsageData) {
if promResult == nil {
return
}
if promResult.Type() == pmodel.ValVector {
matrix := promResult.(pmodel.Vector)
for _, m := range matrix {
v := m.Value
promLable := string(m.Metric[pmodel.LabelName("type")])... | {
result, _, err = promQLAPI.Query(ctx, promQL, queryTime)
if err == nil {
break
}
time.Sleep(100 * time.Millisecond)
} | conditional_block |
data_window.go | HitRatioGTE0Count atomic.Uint64
// CurrentCoprCacheHitRatioGTE1Count is CurrentCoprCacheHitRatioGTE1Count
CurrentCoprCacheHitRatioGTE1Count atomic.Uint64
// CurrentCoprCacheHitRatioGTE10Count is CurrentCoprCacheHitRatioGTE10Count
CurrentCoprCacheHitRatioGTE10Count atomic.Uint64
// CurrentCoprCacheHitRatioGTE20Coun... |
func querySQLMetric(ctx context.Context, queryTime time.Time, promQL string) (result pmodel.Value, err error) {
// Add retry to avoid network error.
var prometheusAddr string
for i := 0; i < 5; i++ {
//TODO: the prometheus will be Integrated into the PD, then we need to query the prometheus in PD directly, which... | {
ctx := context.TODO()
promQL := "avg(tidb_executor_statement_total{}) by (type)"
result, err := querySQLMetric(ctx, timepoint, promQL)
if err != nil {
return err
}
analysisSQLUsage(result, sqlResult)
return nil
} | identifier_body |
data_window.go | CacheHitRatioGTE0Count atomic.Uint64
// CurrentCoprCacheHitRatioGTE1Count is CurrentCoprCacheHitRatioGTE1Count
CurrentCoprCacheHitRatioGTE1Count atomic.Uint64
// CurrentCoprCacheHitRatioGTE10Count is CurrentCoprCacheHitRatioGTE10Count
CurrentCoprCacheHitRatioGTE10Count atomic.Uint64
// CurrentCoprCacheHitRatioGTE2... | (ctx context.Context, queryTime time.Time, promQL string) (result pmodel.Value, err error) {
// Add retry to avoid network error.
var prometheusAddr string
for i := 0; i < 5; i++ {
//TODO: the prometheus will be Integrated into the PD, then we need to query the prometheus in PD directly, which need change the quir... | querySQLMetric | identifier_name |
download.rs | ) => {
format_update!([green] &$before, &$after)
};
(chapters, $before:expr => $after:expr) => {
format_update!([blue] $before, $after)
};
(words, $before:expr => $after:expr) => {
format_update!([blue] $before, $after)
};
(timestamp, $before:expr => $after:expr) => {
... | // So I throw in a `match` to "safely" unwrap it and throw a warning if it is not
// present. | random_line_split | |
download.rs | args::{Download, Prompt};
use crate::readable::ReadableDate;
use crate::Requester;
macro_rules! format_update {
(author, $before:expr => $after:expr) => {
format_update!([green] &$before, &$after)
};
(chapters, $before:expr => $after:expr) => {
format_update!([blue] $before, $after)
};
... |
set_printed!();
let status_notice = format!(
"{} has been marked as {} by the author",
format_story!(story),
format_status!(story)
);
match prompt {
Prompt::AssumeYes => {
info!("{}. Checking for an update on it anyways.... | {
continue;
} | conditional_block |
download.rs | args::{Download, Prompt};
use crate::readable::ReadableDate;
use crate::Requester;
macro_rules! format_update {
(author, $before:expr => $after:expr) => {
format_update!([green] &$before, &$after)
};
(chapters, $before:expr => $after:expr) => {
format_update!([blue] $before, $after)
};
... | }
for (id, story) in story_data.iter().filter_map(|(id, story)| {
if selected_ids.contains(id) {
Some((*id, story))
} else {
None
}
}) {
if let StoryStatus::Incomplete = story.status {
continue;
}
set_printed!();
... | {
let selected_ids: Vec<Id> = if ids.is_empty() {
story_data.keys().cloned().collect()
} else {
story_data
.keys()
.filter(|id| ids.contains(id))
.cloned()
.collect()
};
let mut ignored_ids: HashSet<Id> = HashSet::with_capacity(selected_ids... | identifier_body |
download.rs | args::{Download, Prompt};
use crate::readable::ReadableDate;
use crate::Requester;
macro_rules! format_update {
(author, $before:expr => $after:expr) => {
format_update!([green] &$before, &$after)
};
(chapters, $before:expr => $after:expr) => {
format_update!([blue] $before, $after)
};
... | {
Update(Id, Story),
Forced(Id),
}
pub fn download(
config: &Config,
requester: &Requester,
story_data: &mut StoryData,
Download {
force,
prompt,
ref ids,
}: Download,
) -> Result<()> {
let selected_ids: Vec<Id> = if ids.is_empty() {
story_data.keys().cl... | StoryDownload | identifier_name |
asnd.rs | clusive.
#[must_use]
pub fn voice(mut self, voice: u32) -> Self {
assert!(voice < 16, "Voice index {} is >= 16", voice);
self.voice = voice;
self
}
/// Format to use for this sound.
#[must_use]
pub fn format(mut self, format: VoiceFormat) -> Self {
self.format = ... | () -> u32 {
unsafe { ffi::ASND_GetSampleCounter() }
}
/// Returns the samples sent from the IRQ in one tick.
pub fn get_samples_per_tick() -> u32 {
unsafe { ffi::ASND_GetSamplesPerTick() }
}
/// Sets the global time, in milliseconds.
pub fn set_time(time: u32) {
unsafe ... | get_sample_counter | identifier_name |
asnd.rs | () -> Self {
unsafe {
ffi::ASND_Init();
}
Self
}
/// De-initializes the asnd lib. This is also called when `Asnd` gets dropped.
pub fn end() {
unsafe {
ffi::ASND_End();
}
}
/// Pauses if true and resumes if false.
pub fn pause(sh... | {
assert!(voice < 16, "Voice index {} is >= 16", voice);
unsafe { ffi::ASND_TestPointer(voice as i32, pointer as *mut _) }
} | identifier_body | |
asnd.rs | ) {
unsafe {
ffi::ASND_SetTime(time);
}
}
/// Sets a global callback for general purposes. It is called by the IRQ.
pub fn set_callback<F>(callback: Option<unsafe extern "C" fn()>) {
unsafe {
ffi::ASND_SetCallback(callback);
}
}
/// Returs th... | } | random_line_split | |
dg.go | 推广者-物料精选 )
* taobao.tbk.dg.optimus.material
* @line https://open.taobao.com/api.htm?docId=33947&docType=2
*/
func (d *dg) OptimusMaterial(adzoneId int64, others ...map[string]string) (res *OptimusMaterialResponse, err error) {
params := make(map[string]string)
if len(others) > 0 {
params = others[0]
}
params["... | `jso | identifier_name | |
dg.go |
// 搜索响应数据结构体
type MaterialOptionalResponse struct {
Response struct {
TotalResults int `json:"total_results"`
ResultList struct {
MapData []MaterialOptionalData `json:"map_data"`
} `json:"result_list"`
} `json:"tbk_dg_material_optional_response"`
}
/**
* (通用物料搜索API(导购))
* taobao.tbk.dg.material.option... | {
return &dg{Client: t}
} | identifier_body | |
dg.go | JuPlayEndTime string `json:"ju_play_end_time"`
JuPlayStartTime string `json:"ju_play_start_time"`
PlayInfo string `json:"play_info"`
TmallPlayActivityEndTime int64 `json:"tmall_play_activity_end_time"`
TmallPlayActivityStartTime int64 `json:"tmall_play_a... | type OptimusMaterialResponse struct {
Response struct {
ResultList struct {
MapData []struct {
MaterialOptionalData | random_line_split | |
dg.go | TljInstanceReport(RightsId string) (res *TljReportResponse, err error) {
_, err = v.Client.httpPost("taobao.tbk.dg.vegas.tlj.instance.report", map[string]string{
"rights_id": RightsId,
}, &res)
return
}
type LbTljConf struct {
SecurityLevel int `json:"security_level"` // 安全等级
UseStartTime ... | conditional_block | ||
path.rs | ]
pub fn get_file_name(full_path: &str) -> Option<&str> {
match full_path.rfind('\\') {
None => Some(full_path), // if no backslash, the whole string is the file name
Some(idx) => if idx == full_path.chars().count() - 1 {
None // last char is '\\', no file name
} else {
Some(&full_path[idx + 1..])
... | },
}
}
}
| random_line_split | |
path.rs | is a high-level abstraction over [`HFINDFILE`](crate::HFINDFILE)
/// iteration functions.
///
/// # Examples
///
/// ```no_run
/// use winsafe::{self as w, prelude::*};
///
/// // Ordinary for loop
/// for file_path in w::path::dir_walk("C:\\Temp") {
/// let file_path = file_path?;
/// println!("{}"... |
/// Extracts the full path, but the last part.
///
/// # Examples
///
/// ```no_run
/// use winsafe::{self as w, prelude::*};
///
/// let p = w::path::get_path("C:\\Temp\\xx\\a.txt"); // C:\Temp\xx
/// let q = w::path::get_path("C:\\Temp\\xx\\"); // C:\Temp\xx
/// let r = w::path::get_path("C:\\Temp\\... | {
match full_path.rfind('\\') {
None => Some(full_path), // if no backslash, the whole string is the file name
Some(idx) => if idx == full_path.chars().count() - 1 {
None // last char is '\\', no file name
} else {
Some(&full_path[idx + 1..])
},
}
} | identifier_body |
path.rs | get_path(&dbg).unwrap(), // exe name
).unwrap(),
).unwrap()
.to_owned(),
)
}
/// Returns the path of the current EXE file, without the EXE filename, and
/// without a trailing backslash.
///
/// In a debug build, the `target\debug` folders will be suppressed.
#[cfg(not(debug_assertions))]
#[must_... | {
return None;
} | conditional_block | |
path.rs | This is a high-level abstraction over [`HFINDFILE`](crate::HFINDFILE)
/// iteration functions.
///
/// # Examples
///
/// ```no_run
/// use winsafe::{self as w, prelude::*};
///
/// // Ordinary for loop
/// for file_path in w::path::dir_walk("C:\\Temp") {
/// let file_path = file_path?;
/// println!... | (full_path: &str, new_extension: &str) -> String {
if let Some(last) = full_path.chars().last() {
if last == '\\' { // full_path is a directory, do nothing
return rtrim_backslash(full_path).to_owned();
}
}
let new_has_dot = new_extension.chars().next() == Some('.');
match full_path.rfind('.') {
N... | replace_extension | identifier_name |
unitconverter.py |
THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
class UnitNames(object):
"""
Unit Names is a namespace to hold units
"""
__slots__ = ()
# bits
bits = "bits"
kbits = "K" + bits
kilobits = kbits
mbits = "M" + bits
megabits = mbits
gbits = "G" + bits
gigab... | (BaseConverter):
"""
The BinaryUnitconverter is a conversion lookup table for binary data
Usage::
converted = old * UnitConverter[old units][new units]
Use class UnitNames to get valid unit names
"""
def __init__(self):
super(BinaryUnitconverter, self).__init__(to_units=binary_... | BinaryUnitconverter | identifier_name |
unitconverter.py |
THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
class UnitNames(object):
"""
Unit Names is a namespace to hold units
"""
__slots__ = ()
# bits
bits = "bits"
kbits = "K" + bits
kilobits = kbits
mbits = "M" + bits
megabits = mbits
gbits = "G" + bits
gigab... |
@property
def bits_to_bytes(self):
"""
List of conversions for bits to bytes
"""
if self._bits_to_bytes is None:
self._bits_to_bytes = self.conversions(conversion_factor=TO_BYTE)
return self._bits_to_bytes
@property
def bytes_to_bits(self):
... | """
List of lists of prefix conversions
"""
if self._prefix_conversions is None:
# start with list that assumes value has no prefix
# this list is for 'bits' or 'bytes'
# the values will be 1, 1/kilo, 1/mega, etc.
start_list = [self.kilo_prefix**(-... | identifier_body |
unitconverter.py |
THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
class UnitNames(object):
"""
Unit Names is a namespace to hold units
"""
__slots__ = ()
# bits
bits = "bits"
kbits = "K" + bits
kilobits = kbits
mbits = "M" + bits
megabits = mbits
gbits = "G" + bits
gigab... |
# from bytes to bits or bytes
for index, units in enumerate(self.byte_units):
self[units] = dict(list(zip(self.to_units, self.bytes_to_bits[index] +
self.prefix_conversions[index])))
return
# end class BaseConverter
bit_units = [UnitName... | self[units] = dict(list(zip(self.to_units, self.prefix_conversions[index] +
self.bits_to_bytes[index]))) | conditional_block |
unitconverter.py |
THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
class UnitNames(object):
"""
Unit Names is a namespace to hold units
"""
__slots__ = ()
# bits
bits = "bits"
kbits = "K" + bits
kilobits = kbits
mbits = "M" + bits
megabits = mbits
gbits = "G" + bits
gigab... | def build_conversions(self):
"""
builds the dictionary
"""
# from bits to bits or bytes
for index, units in enumerate(self.bit_units):
self[units] = dict(list(zip(self.to_units, self.prefix_conversions[index] +
self.bits_to_bytes... | return converter_list
| random_line_split |
timeloop.py | , OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import functools
import inspect
import os
import subprocess
import sys
import timeit
import argparse
import copy
import re
import libconf
import yaml
from common im... | print(' H-pad =', hpad)
print(' W-stride =', wstride)
print(' H-stride =', hstride)
print()
else:
print('Equivalence Test: can we convert WU problem to FW and use cnn-layer.cfg? (at least in the dense case?)')
print('Workload Dimensions:')
print(' W ... | print(' P =', p)
print(' Q =', q)
print(' N =', n)
print(' W-pad =', wpad) | random_line_split |
timeloop.py | , OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import functools
import inspect
import os
import subprocess
import sys
import timeit
import argparse
import copy
import re
import libconf
import yaml
from common im... |
else:
config['problem']['R'] = p
config['problem']['S'] = q
config['problem']['P'] = r
config['problem']['Q'] = s
config['problem']['C'] = n
config['problem']['K'] = c
config['problem']['N'] = k
config['problem']['Wstride'] = wstride
config['problem']... | config['problem']['R'] = r
config['problem']['S'] = s
config['problem']['P'] = p
config['problem']['Q'] = q
config['problem']['C'] = c
if not depthwise:
config['problem']['K'] = k
config['problem']['N'] = n | conditional_block |
timeloop.py | =', hstride)
print()
else:
print('Equivalence Test: can we convert WU problem to FW and use cnn-layer.cfg? (at least in the dense case?)')
print('Workload Dimensions:')
print(' W =', w)
print(' H =', h)
print(f' C <- N {n}')
print(f' K <- C ... | with open(logfile_path, "w") as outfile:
this_file_path = os.path.abspath(inspect.getfile(inspect.currentframe()))
if not dense:
timeloop_executable_location = os.path.join(
os.path.dirname(this_file_path), '..', 'build', 'timeloop-mapper')
else:
... | identifier_body | |
timeloop.py | , OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import functools
import inspect
import os
import subprocess
import sys
import timeit
import argparse
import copy
import re
import libconf
import yaml
from common im... | (l):
return functools.reduce(lambda x, y: x * y, l)
def rewrite_workload_bounds(src, dst, workload_bounds, model, layer, batchsize, dataflow, phase, terminate, threads, synthetic, sparsity, save, replication, array_width, glb_scaling, dense): # backward_padding
w, h, c, n, k, s, r, wpad, hpad, wstride, hstri... | prod | identifier_name |
ops.py | .geometry.Polygon
g1 = geojson.loads(s)
# covert to shapely.geometry.polygon.Polygon
g2 = shape(g1)
if feat['properties']['color'] == 'red': # red for the burnt region
burnt_polys.append(g2)
else: # for the building poly
building_polys.append([g2, [fea... | plot_array | identifier_name | |
ops.py |
feats = stack.ravel().reshape(stack.shape[0] * stack.shape[1], stack.shape[2])
return feats
def calc_rsi(image):
"""Remote sensing indices for vegetation, built-up, and bare soil."""
# roll axes to conventional row,col,depth
img = np.rollaxis(image, 0, 3)
# bands: Coastal(0), Blue(1), Gre... | stack = np.dstack([img, rsi]) | conditional_block | |
ops.py | R + Y))
normnir = old_div(NIR1, (NIR1 + R + G))
psri = old_div((R - B), RE)
rey = old_div((RE - Y), (RE + Y))
rvi = old_div(NIR1, R)
sa = old_div(((Y + R) * 0.35), 2) + old_div((0.7 * (NIR1 + NIR2)), 2) - 0.69
vi1 = old_div((10000 * NIR1), (RE) ** 2)
vire = old_div(NIR1, RE)
br = (old_di... | """Convert shapes into geojson for the groundtruth."""
results = ({
'type': 'Feature',
'properties': {'color': 'red'},
'geometry': geo.mapping(r)}
for r in burnt_polys)
list_results = list(results)
# append the building footprints to geojson
results_buildings = ({
... | identifier_body | |
ops.py | - R), (NIR1 + R))
ndvi35 = old_div((G - R), (G + R))
ndvi84 = old_div((NIR2 - Y), (NIR2 + Y))
nirry = old_div((NIR1), (R + Y))
normnir = old_div(NIR1, (NIR1 + R + G))
psri = old_div((R - B), RE)
rey = old_div((RE - Y), (RE + Y))
rvi = old_div(NIR1, R)
sa = old_div(((Y + R) * 0.35), 2) +... | return response.content
#partials
get_model = partial(get_link, model_url=RF_model_link) #gets RF model response content
get_geojson = partial(get_link, model_url=buildings_geojson_link) #gets building geojson response content
def reproject(geom, from_proj='EPSG:4326', to_proj='EPSG:26942'):
"""Project from E... | random_line_split | |
dwi_corr_util.py | class MRdegibbsOutputSpec(TraitedSpec):
out_file = File(desc = "the output unringed DWI image", exists = True)
class MRdegibbs(CommandLine):
"""Use MRTrix3 degibbs command for removing the gibbs ringing artefact.
For more information, see
<https://mrtrix.readthedocs.io/en/latest/reference/commands... | super(Eddy, self).__init__(**inputs)
self.inputs.on_trait_change(self._num_threads_update, 'num_threads')
if not isdefined(self.inputs.num_threads):
self.inputs.num_threads = self._num_threads
else:
self._num_threads_update()
self.inputs.on_trait_change(self._use_... | identifier_body | |
dwi_corr_util.py | linear',
'quadratic',
argstr='--slm=%s',
desc='Second level EC model')
fep = traits.Bool(
False, argstr='--fep', desc='Fill empty planes in x- or y-directions')
interp = traits.Enum(
'spline',
'trilinear',
argstr='--interp=%s',
desc='Interpolation ... | outputs['out_shell_alignment_parameters'] = \
out_shell_alignment_parameters | conditional_block | |
dwi_corr_util.py | exists = True)
class MRdegibbs(CommandLine):
"""Use MRTrix3 degibbs command for removing the gibbs ringing artefact.
For more information, see
<https://mrtrix.readthedocs.io/en/latest/reference/commands/mrdegibbs.html>
"""
_cmd = '/a/software/mrtrix/3.0-rc2/ubuntu-xenial-amd64/bin/mrdegibbs'
... | self._num_threads = self.inputs.num_threads
if not isdefined(self.inputs.num_threads): | random_line_split | |
dwi_corr_util.py | Spec(TraitedSpec):
out_file = File(desc = "the output unringed DWI image", exists = True)
class MRdegibbs(CommandLine):
"""Use MRTrix3 degibbs command for removing the gibbs ringing artefact.
For more information, see
<https://mrtrix.readthedocs.io/en/latest/reference/commands/mrdegibbs.html>
... | _num_threads_update | identifier_name | |
lib.rs | values and
//! intuitive syntax.
//!
//! - `local-offset` (_implicitly enables `std`_)
//!
//! This feature enables a number of methods that allow obtaining the system's
//! UTC offset.
//!
//! - `large-dates`
//!
//! By default, only years within the ±9999 range (inclusive) are supported.
//! If you need su... | Err(error) => return Err(error),
}
};
}
/// Try to unwrap an expression, returning if not possible.
///
/// This is similar to the `?` operator, but is usable in `const` contexts.
macro_rules! const_try_opt {
($e:expr) => {
match $e {
Some(value) => value,
No... | macro_rules! const_try {
($e:expr) => {
match $e {
Ok(value) => value, | random_line_split |
durconn.go |
stanOptPingInterval int
stanOptPingMaxOut int
stanOptPubAckWait time.Duration
connectCb func(stan.Conn)
disconnectCb func(stan.Conn)
subscribeCb func(sc stan.Conn, spec MsgSpec)
wg sync.WaitGroup // wait for go routines
connectMu sync.Mutex // at most on connect can be ... |
dc.connectMu.Lock()
defer dc.connectMu.Unlock()
// Reset connection: release old connection
{
dc.mu.Lock()
if dc.closed {
dc.mu.Unlock()
dc.logger.Info("closed when reseting connection")
return
}
sc := dc.sc
scStaleCh := dc.scStaleCh
dc.sc = nil
dc.scStaleCh = nil
dc.mu.Unlock()
if sc... | {
time.Sleep(dc.reconnectWait)
} | conditional_block |
durconn.go | .Duration
stanOptPingInterval int
stanOptPingMaxOut int
stanOptPubAckWait time.Duration
connectCb func(stan.Conn)
disconnectCb func(stan.Conn)
subscribeCb func(sc stan.Conn, spec MsgSpec)
wg sync.WaitGroup // wait for go routines
connectMu sync.Mutex // at most on connec... | subs: make(map[[2]string]*subscription),
}
defer func() {
if err != nil {
dc.runner.Close()
}
}()
for _, opt := range opts {
if err = opt(dc); err != nil {
return nil, err
}
}
dc.goConnect(false)
return dc, nil
}
// NewPublisher creates a publisher using specified encoder.
func... | stanOptPingMaxOut: DefaultStanPingMaxOut,
stanOptPubAckWait: DefaultStanPubAckWait,
connectCb: func(_ stan.Conn) {},
disconnectCb: func(_ stan.Conn) {},
subscribeCb: func(_ stan.Conn, _ MsgSpec) {}, | random_line_split |
durconn.go | spec, msg, encoder, cb)
}
}
// NewSubscriber creates a subscriber using specified decoder.
func (dc *DurConn) NewSubscriber(decoder npenc.Decoder) MsgSubscriberFunc {
return func(spec MsgSpec, queue string, handler MsgHandler, opts ...interface{}) error {
sub := &subscription{
spec: spec,
queue: ... | {
dc.mu.Lock()
if dc.closed {
dc.mu.Unlock()
return
}
sc := dc.sc
scStaleCh := dc.scStaleCh
dc.sc = nil
dc.scStaleCh = nil
dc.closed = true
dc.mu.Unlock()
if sc != nil {
sc.Close()
close(scStaleCh)
}
dc.runner.Close()
dc.wg.Wait() | identifier_body | |
durconn.go |
stanOptPingInterval int
stanOptPingMaxOut int
stanOptPubAckWait time.Duration
connectCb func(stan.Conn)
disconnectCb func(stan.Conn)
subscribeCb func(sc stan.Conn, spec MsgSpec)
wg sync.WaitGroup // wait for go routines
connectMu sync.Mutex // at most on connect can be ... | (subs []*subscription, sc stan.Conn, scStaleCh chan struct{}) {
success := make([]bool, len(subs))
for {
n := 0
for i, sub := range subs {
if success[i] {
// Already success.
n++
continue
}
if err := dc.subscribe(sub, sc); err != nil {
continue
}
success[i] = true
n++
select... | subscribeAll | identifier_name |
circuitpusher.py | --src {IP} --dst {IP} --add --name {circuit-name}
adds a new circuit between src and dst devices Currently ip circuit is supported. ARP is automatically supported.
Currently a simple circuit record storage is provided in a text file circuits.json in the working directory.
The file is not pr... |
else:
lines={}
if args.action=='add':
circuitDb = open('./circuits.json','a')
for line in lines:
data = json.loads(line)
if data['name']==(args.circuitName):
print "Circuit %s exists already. Use new name to create." % args.circuitName
sys.exit()
else:... | circuitDb = open('./circuits.json','r')
lines = circuitDb.readlines()
circuitDb.close() | conditional_block |
circuitpusher.py | ip --src {IP} --dst {IP} --add --name {circuit-name}
adds a new circuit between src and dst devices Currently ip circuit is supported. ARP is automatically supported.
Currently a simple circuit record storage is provided in a text file circuits.json in the working directory.
The file is not... | controllerRestIp = args.controllerRestIp
# first check if a local file exists, which needs to be updated after add/delete
if os.path.exists('./circuits.json'):
circuitDb = open('./circuits.json','r')
lines = circuitDb.readlines()
circuitDb.close()
else:
lines={}
if args.action=='add':
circuitDb =... | args = parser.parse_args()
print args
| random_line_split |
play15old2.rs | ;
impl Board {
pub fn new() -> Self {
let mut arr = [[0u8; WIDTH]; HEIGHT];
for y in 0..WIDTH {
for x in 0..HEIGHT {
arr[y][x] = ((y * WIDTH + x + 1) % (WIDTH * HEIGHT)) as u8
}
}
Board(arr)
}
pub fn from_array(arr: [[u8; WIDTH]; HEIG... | BoardCreateError | identifier_name | |
play15old2.rs | .get_mut(arr[y][x] as usize).map(|x| *x += 1);
}
}
let has_one_of_all = tile_count.iter().all(|x| *x == 1);
if has_one_of_all {
Ok(Board(arr))
} else {
Err(BoardCreateError)
}
}
pub fn size(&self) -> (usize, usize) {
(WIDTH, HE... |
#[inline(always)]
pub fn swap(&mut self, p1: (usize, usize), p2: (usize, usize)) {
let arr = &mut self.0;
let t1 = arr[p1.1][p1.0];
let t2 = arr[p2.1][p2.0];
arr[p1.1][p1.0] = t2;
arr[p2.1][p2.0] = t1;
}
pub fn apply(&mut self, dir: Dir) -> Result<(), ()> {
... | {
for y in 0..HEIGHT {
for x in 0..WIDTH {
if self.0[y][x] == 0 {
return (x, y);
}
}
}
panic!()
} | identifier_body |
play15old2.rs | zx, zy), (zx, zy + 1));
Ok(())
}
Dir::Left if zx > 0 => {
self.swap((zx, zy), (zx - 1, zy));
Ok(())
}
Dir::Up if zy > 0 => {
self.swap((zx, zy), (zx, zy - 1));
Ok(())
}
... | random_line_split | ||
code_quality_eval.py | (hash, type):
"""
Method used to search for a specific blob, commit or tree.
If a tree is searched for, the result is splitted into its components (blobs and directories),
which are again splitted into their mode, hash and name.
In the case of a commit, we split the information string and the tree hash and
pa... | search | identifier_name | |
code_quality_eval.py | {}
# delete contents
open('introductions.csv', 'w').close()
# for every commit, we look up whether the author included a CI file,
# that did not exist in the parent commit
for count, commit in enumerate(commits):
# status update
if (count + 1) % 50 == 0:
print count + 1, ' / ', len(commits)
tree_has... |
#### Start building the regular expression that will be used to search for unit testing libraries,
#### in the commit's blobs ####
# Java
java_lib = ['io.restassured', 'org.openqa.selenium', 'org.spockframework', 'jtest',
'org.springframework.test', 'org.dbunit', 'org.jwalk', 'org.mockito', 'org.junit']
java_regex =... | """
Method used to find the neighbours of a given author, i.e. the authors that
affected the given author's use of good coding practices.
A timestamp is also given to define the time till which we find the connections.
"""
out = bash('echo "'+ author + '" | ~/lookup/getValues a2P')
pr = [x for x in out.strip().sp... | identifier_body |
code_quality_eval.py | which are again splitted into their mode, hash and name.
In the case of a commit, we split the information string and the tree hash and
parent's commit hash are returned
"""
out = bash('echo ' + hash + ' | ~/lookup/showCnt ' + type)
if type == 'tree':
return [blob.split(';') for blob in out.strip().split('\... |
If a tree is searched for, the result is splitted into its components (blobs and directories), | random_line_split | |
code_quality_eval.py | {}
# delete contents
open('introductions.csv', 'w').close()
# for every commit, we look up whether the author included a CI file,
# that did not exist in the parent commit
for count, commit in enumerate(commits):
# status update
if (count + 1) % 50 == 0:
print count + 1, ' / ', len(commits)
tree_has... |
# controlling for the case of multiple parent commits
all_parent_CI = False
for parent in parent_commit_hash.split(':'):
# controlling for the case of no parent commits
if parent == '':
break
parent_tree_hash = search(parent, 'commit')[0]
if parent_tree_hash not in CI_checked:
parent... | CI_checked[tree_hash] = ci_lookup(tree_hash) | conditional_block |
aas220_poster.py | sim_light_curve.mjd
sim_mag = sim_light_curve.mag
sim_err = sim_light_curve.error
while True:
if len(sim_mjd) < min_num_observations: break
dcs = simu.compute_delta_chi_squared((sim_mjd,... |
def systematics_9347(): | random_line_split | |
aas220_poster.py | for row in low_cadence: ogle_low_cadence_fields.append(coverageplots.OGLEField(row["ra"], row["dec"]))
coverage_plot = coverageplots.PTFCoveragePlot(figsize=(30,15), projection="aitoff")
coverage_plot.addFields(ptf_fields, label="PTF", color_by_observations=True)
coverage_plot.addFields(ogle_low_ca... | raw_field_data = pf.open("data/exposureData.fits")[1].data
unq_field_ids = np.unique(raw_field_data.field_id)
ptf_fields = []
for field_id in unq_field_ids:
one_field_data = raw_field_data[raw_field_data.field_id == field_id]
mean_ra = np.mean(one_field_data.ra) / 15.
mean_dec =... | identifier_body | |
aas220_poster.py | np.sum(detection_efficiency_distribution * event_rate_distribution / 365. * bin_widths) * 1095. # days of Praesepe obs.
print "Number of events in our Praesepe sample (102 days): {} +/- {}".format(N_exp, np.sqrt(N_exp))
print "Number of events if we had observed it consistently for 3 years: {} +/- {}".for... | variability_indices | identifier_name | |
aas220_poster.py | /60./np.cos(dec_rad)), height=np.radians(diameter/60.), alpha=.4, edgecolor="g", facecolor="g")
coverage_plot.axis.add_patch(circle)
"""
coverage_plot.addLegend()
coverage_plot.title.set_fontsize(title_font_size)
legendtext = coverage_plot.legend.get_texts()
plt.setp(legendtext, fontsiz... |
clumps.append(sparse_samples)
mjd = np.concatenate(tuple(clumps))
plt.plot(mjd, [1.]*len(mjd), 'ro', alpha=0.4)
plt.show()
elif sampling == "uniform":
mjd = ... | data_dict = {"clumpy" : {1. : [], 10. : [], 100 : []}, "uniform" : {1. : [], 10. : [], 100 : []}}
for timescale in [1., 10., 100.]:
for sampling in ["clumpy", "uniform"]: #, "random"]:
if sampling == "random":
mjd = np.random.random(max_num_observations)*... | conditional_block |
get_models.py | v
return c
def consolidate_json(json_list):
json_obj = {}
for json in json_list:
json_obj.update(json)
json_dict = OrderedDict(sorted(json_obj.items(), key=lambda t: t[1]['type']))
return json_dict
def get_summary(data):
summary = {}
for device, info... | sfp = []
sfp_plus = []
if isinstance(ports, (list, dict)):
#standard = [x for x in range(1,len(ports)+1,1)] | random_line_split | |
get_models.py |
def update(self,iteration):
iteration = max(min(iteration, self.total), 0)
str_format = "{0:." + str(self.decimals) + "f}"
percents = str_format.format(100 * (iteration / float(self.total)))
filled_length = int(round(self.bar_length * iteration / float(self.total)))
... | self.total = total
self.prefix = prefix
self.suffix = suffix
self.decimals = decimals
self.bar_length = bar_length
self.prev_output_len = 0 | identifier_body | |
get_models.py | = len(diagram)
standard, sfp, sfp_plus = extract_ports_list(info['ports'])
if len(standard) > 0:
log.info('ports %s are standard ports' % standard )
standard = len(standard)
... | ():
| identifier_name | |
get_models.py | ('Found in file %s on line %s: %s' % (file, i+1, match.group()))
models_files.append(file)
continue
return models_files
def find_json(files, pattern_match, all=False):
pattern = re.compile(r".*\.exports=(\{.*?\}\}\}\})\}.*")
json_obj = []
for file in files:
s... | else:
log.error('OK, the first ports must be standard, sfp, or sfp+ ports. try again')
log.debug('Device: %s added' % new_models[type][device])
log.info('... | models[type][device]['order'] = [2,0,1]
| conditional_block |
webhdfs.rs | ");
for input in fs {
let input_path = Path::new(&input);
let output_file = input_path.file_name().expect2("file name must be specified if no output file is given");
let output = target_dir.join(&Path::new(output_file));
... |
};
(client, operation)
}
}
//-------------------------
mod commandline {
/// Prints two-part message to stderr and exits
pub fn error_exit(msg: &str, detail: &str) -> ! {
eprint!("Error: {}", msg);
if detail.is_empty() {
eprintln!()
} else {
... | { error_exit("must specify at least one input file for --get", "") } | conditional_block |
webhdfs.rs | ");
for input in fs {
let input_path = Path::new(&input);
let output_file = input_path.file_name().expect2("file name must be specified if no output file is given");
let output = target_dir.join(&Path::new(output_file));
... |
}
#[derive(Debug)]
pub enum CmdLn {
Switch(String),
Arg(String),
Item(String)
}
impl std::fmt::Display for CmdLn {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
CmdLn::Switch(s) => write!(fmt, "Switc... | {
match self {
Some(v) => v,
None => error_exit(msg, "")
}
} | identifier_body |
webhdfs.rs | dir");
for input in fs {
let input_path = Path::new(&input);
let output_file = input_path.file_name().expect2("file name must be specified if no output file is given");
let output = target_dir.join(&Path::new(output_file));
... | impl std::fmt::Display for CmdLn {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
CmdLn::Switch(s) => write!(fmt, "Switch '{}'", s),
CmdLn::Arg(s) => write!(fmt, "Arg '{}'", s),
CmdLn::Item(s) => write!(fmt, "It... | Switch(String),
Arg(String),
Item(String)
}
| random_line_split |
webhdfs.rs | ");
for input in fs {
let input_path = Path::new(&input);
let output_file = input_path.file_name().expect2("file name must be specified if no output file is given");
let output = target_dir.join(&Path::new(output_file));
... | () -> ! {
println!(
"{} ({}) version {}",
env!("CARGO_PKG_DESCRIPTION"),
env!("CARGO_PKG_NAME"),
env!("CARGO_PKG_VERSION")
);
std::process::exit(0);
}
fn usage() -> ! {
println!("USAGE:
webhdfs <options>... <command> <files>...
webhdfs -h|--help
webhdfs -v|--version
opt... | version | identifier_name |
deepobject.go | /oapi-codegen/pkg/types"
)
func marshalDeepObject(in interface{}, path []string) ([]string, error) {
var result []string
switch t := in.(type) {
case []interface{}:
// For the array, we will use numerical subscripts of the form [x],
// in the same order as the array.
for i, iface := range t {
newPath := a... | (dst interface{}, paramName string, params url.Values) error {
// Params are all the query args, so we need those that look like
// "paramName["...
var fieldNames []string
var fieldValues []string
searchStr := paramName + "["
for pName, pValues := range params {
if strings.HasPrefix(pName, searchStr) {
// tr... | UnmarshalDeepObject | identifier_name |
deepobject.go | api-codegen/pkg/types"
)
func marshalDeepObject(in interface{}, path []string) ([]string, error) {
var result []string
switch t := in.(type) {
case []interface{}:
// For the array, we will use numerical subscripts of the form [x],
// in the same order as the array.
for i, iface := range t {
newPath := app... |
pv, found := f.fields[fieldName]
if !found {
pv = fieldOrValue{
fields: make(map[string]fieldOrValue),
}
f.fields[fieldName] = pv
}
pv.appendPathValue(path[1:], value)
}
func makeFieldOrValue(paths [][]string, values []string) fieldOrValue {
f := fieldOrValue{
fields: make(map[string]fieldOrValue),
... | {
f.fields[fieldName] = fieldOrValue{value: value}
return
} | conditional_block |
deepobject.go | /oapi-codegen/pkg/types"
)
func marshalDeepObject(in interface{}, path []string) ([]string, error) {
var result []string
switch t := in.(type) {
case []interface{}:
// For the array, we will use numerical subscripts of the form [x],
// in the same order as the array.
for i, iface := range t {
newPath := a... | fields map[string]fieldOrValue
value string
}
func (f *fieldOrValue) appendPathValue(path []string, value string) {
fieldName := path[0]
if len(path) == 1 {
f.fields[fieldName] = fieldOrValue{value: value}
return
}
pv, found := f.fields[fieldName]
if !found {
pv = fieldOrValue{
fields: make(map[strin... | }
type fieldOrValue struct { | random_line_split |
deepobject.go | api-codegen/pkg/types"
)
func marshalDeepObject(in interface{}, path []string) ([]string, error) {
var result []string
switch t := in.(type) {
case []interface{}:
// For the array, we will use numerical subscripts of the form [x],
// in the same order as the array.
for i, iface := range t {
newPath := app... |
func makeFieldOrValue(paths [][]string, values []string) fieldOrValue {
f := fieldOrValue{
fields: make(map[string]fieldOrValue),
}
for i := range paths {
path := paths[i]
value := values[i]
f.appendPathValue(path, value)
}
return f
}
func UnmarshalDeepObject(dst interface{}, paramName string, params u... | {
fieldName := path[0]
if len(path) == 1 {
f.fields[fieldName] = fieldOrValue{value: value}
return
}
pv, found := f.fields[fieldName]
if !found {
pv = fieldOrValue{
fields: make(map[string]fieldOrValue),
}
f.fields[fieldName] = pv
}
pv.appendPathValue(path[1:], value)
} | identifier_body |
server.go |
if tc, ok := conn.(*net.TCPConn); ok { // tcp请求需要设置keepAlive保证链接的稳定性能
tc.SetKeepAlive(true)
tc.SetKeepAlivePeriod(time.Minute * 5) // 5分钟没有响应报错
tc.SetLinger(10) // 关闭连接的行为 设置数据在断开时候也能在后台发送
}
conn, ok := s.Plugins.DoPostConnAccept(conn)
if !ok { // 不允许链接则关闭(可能是限流没通过,验证没通过,业务方面的自... | 的
func (s *Server) handleRequestForFunction(ctx context.Context, request *protocol.Message) (*protocol.Message, error) { | conditional_block | |
server.go | , false)
if size > 65536 {
size = 65536
}
buf = buf[:size]
log.ErrorF("conn 发生panic,原因%s, 客户端地址%s, 堆栈信息 %s", err, conn.RemoteAddr(), buf)
}
s.connMu.Lock()
delete(s.activeConn, conn)
s.connMu.Unlock()
s.Plugins.DoPostConnClose(conn)
}()
// 判断此时服务是否已经关闭
if s.isShutdown() {
s.closeChannel(... | defer ObjectPool.Put(funcType.responseType, responseType) | random_line_split | |
server.go | n处理
func (s *Server) serveListener(ln net.Listener) error {
// 定义临时错误的延迟时间
var tempDelay time.Duration
s.connMu.Lock()
s.ln = ln
s.connMu.Unlock()
for {
conn, err := ln.Accept()
if err != nil {
select {
case <-s.doneChan:
return ErrServerClosed
default:
}
// 如果错误断言为网络错误,且是一个临时的(比如当时网络环境差,... | erCon | identifier_name | |
server.go | // 看看是否注册了函数的调用
if _, ok := service.function[methodName]; ok {
protocol.FreeMsg(response) // 这里创建对象要回收的
return s.handleRequestForFunction(ctx, request)
}
err = errors.New(fmt.Sprintf("不能找到服务提供者%s下方法名为%s的方法", serviceName, methodName))
return handleError(response, err)
}
requestType := ObjectPool.Get(me... | identifier_body | ||
prefilter.rs |
// them.
if !self.ascii_case_insensitive {
if let Some(pre) = self.memmem.build() {
return Some(pre);
}
}
match (self.start_bytes.build(), self.rare_bytes.build()) {
// If we could build both start and rare prefilters, then there are
... | {
/// Whether this prefilter should account for ASCII case insensitivity or
/// not.
ascii_case_insensitive: bool,
/// A set of rare bytes, indexed by byte value.
rare_set: ByteSet,
/// A set of byte offsets associated with bytes in a pattern. An entry
/// corresponds to a particular bytes ... | RareBytesBuilder | identifier_name |
prefilter.rs | rare_set: ByteSet,
/// A set of byte offsets associated with bytes in a pattern. An entry
/// corresponds to a particular bytes (its index) and is only non-zero if
/// the byte occurred at an offset greater than 0 in at least one pattern.
///
/// If a byte's offset is not representable in 8 bits, t... | {
self.rare_set.add(byte);
self.count += 1;
self.rank_sum += freq_rank(byte) as u16;
} | conditional_block | |
prefilter.rs |
// them.
if !self.ascii_case_insensitive {
if let Some(pre) = self.memmem.build() {
return Some(pre);
}
}
match (self.start_bytes.build(), self.rare_bytes.build()) {
// If we could build both start and rare prefilters, then there are
... |
}
/// A builder for constructing a rare byte prefilter.
///
/// A rare byte prefilter attempts to pick out a small set of rare bytes that
/// occurr in the patterns, and then quickly scan to matches of those rare
/// bytes.
#[derive(Clone, Debug)]
struct RareBytesBuilder {
/// Whether this prefilter should accoun... | {
use crate::util::primitives::PatternID;
self.0.find(&haystack[span]).map_or(Candidate::None, |i| {
let start = span.start + i;
let end = start + self.0.needle().len();
// N.B. We can declare a match and use a fixed pattern ID here
// because a Memmem pr... | identifier_body |
prefilter.rs | (bytes);
}
}
}
/// A type that wraps a packed searcher and implements the `Prefilter`
/// interface.
#[derive(Clone, Debug)]
struct Packed(packed::Searcher);
impl PrefilterI for Packed {
fn find_in(&self, haystack: &[u8], span: Span) -> Candidate {
self.0
.find_in(&haystack, span)
... | }
let (mut bytes, mut len) = ([0; 3], 0); | random_line_split | |
code.go | s' is a read only variable", "You cannot set the given variable as it is a read-only variable.")
VT03011 = errorWithoutState("VT03011", vtrpcpb.Code_INVALID_ARGUMENT, "invalid value type: %v", "The given value type is not accepted.")
VT03012 = errorWithoutState("VT03012", vtrpcpb.Code_INVALID_ARGUMENT, "invalid synta... | VT03022 = errorWithoutState("VT03022", vtrpcpb.Code_INVALID_ARGUMENT, "column %v not found in %v", "The given column cannot be found.")
VT03023 = errorWithoutState("VT03023", vtrpcpb.Code_INVALID_ARGUMENT, "INSERT not supported when targeting a key range: %s", "When targeting a range of shards, Vitess does not know w... | VT03021 = errorWithoutState("VT03021", vtrpcpb.Code_INVALID_ARGUMENT, "ambiguous column reference: %v", "The given column is ambiguous. You can use a table qualifier to make it unambiguous.") | random_line_split |
code.go | keyspace<:shard><@type> or keyspace<[range]><@type> (<> are optional)", "A database must be selected.")
VT09006 = errorWithoutState("VT09006", vtrpcpb.Code_FAILED_PRECONDITION, "%s VITESS_MIGRATION works only on primary tablet", "VITESS_MIGRATION commands work only on primary tablets, you must send such commands to a... | {
return func(args ...any) *VitessError {
s := short
if len(args) != 0 {
s = fmt.Sprintf(s, args...)
}
return &VitessError{
Err: New(code, id+": "+s),
Description: long,
ID: id,
}
}
} | identifier_body | |
code.go | .")
VT09005 = errorWithState("VT09005", vtrpcpb.Code_FAILED_PRECONDITION, NoDB, "no database selected: use keyspace<:shard><@type> or keyspace<[range]><@type> (<> are optional)", "A database must be selected.")
VT09006 = errorWithoutState("VT09006", vtrpcpb.Code_FAILED_PRECONDITION, "%s VITESS_MIGRATION works only on... | {
s = fmt.Sprintf(s, args...)
} | conditional_block | |
code.go | index column '%v' in the column list", "A vindex column is mandatory for the insert, please provide one.")
VT09004 = errorWithoutState("VT09004", vtrpcpb.Code_FAILED_PRECONDITION, "INSERT should contain column list or the table should have authoritative columns in vschema", "You need to provide the list of columns you... | Error | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.