file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
tags.rs
use crate::{ResponseValue, ViewWrap}; use std::fmt::Debug; use htmldom_read::{Node}; use crate::events::OnClick; use std::marker::PhantomData; use std::ops::{Deref, DerefMut}; use std::fmt::Formatter; use std::sync::Arc; /// The functions that allow to load images concurrently. pub mod image_loader { use std::sync...
pub fn set_href<T: AsRef<str>>(&mut self, href: T) { self.set_attribute("href", href.as_ref()) } pub fn onclick(&self) -> &OnClick<A> { &self.onclick } pub fn onclick_mut(&mut self) -> &mut OnClick<A> { &mut self.onclick } } impl ImageContent for Img { fn set_im...
{ if let Some(s) = self.attribute("href") { s } else { String::new() } }
identifier_body
tags.rs
use crate::{ResponseValue, ViewWrap}; use std::fmt::Debug; use htmldom_read::{Node}; use crate::events::OnClick; use std::marker::PhantomData; use std::ops::{Deref, DerefMut}; use std::fmt::Formatter; use std::sync::Arc; /// The functions that allow to load images concurrently. pub mod image_loader { use std::sync...
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
use crate::{ResponseValue, ViewWrap}; use std::fmt::Debug; use htmldom_read::{Node}; use crate::events::OnClick; use std::marker::PhantomData; use std::ops::{Deref, DerefMut}; use std::fmt::Formatter; use std::sync::Arc; /// The functions that allow to load images concurrently. pub mod image_loader { use std::sync...
(node: &Node) -> Option<Self> { let tag_name = node.tag_name(); if let Some(tag_name) = tag_name { let tag_name = TagName::from(tag_name); Some(tag_name) } else { None } } /// Try creating implementation of the Element from this node. /// ...
try_from_node
identifier_name
destination.rs
use super::pandas_columns::{ BooleanBlock, BytesBlock, DateTimeBlock, Float64Block, HasPandasColumn, Int64Block, PandasColumn, PandasColumnObject, StringBlock, }; use super::types::{PandasDType, PandasTypeSystem}; use anyhow::anyhow; use connectorx::{ ConnectorAgentError, Consume, DataOrder, Destination, De...
let code = format!( r#"import pandas as pd import numpy as np blocks = [{}] block_manager = pd.core.internals.BlockManager( blocks, [pd.Index(['{}']), pd.RangeIndex(start=0, stop={}, step=1)]) df = pd.DataFrame(block_manager) blocks = [b.values for b in df._mgr.blocks] index = [(i, j) for i, j in zip(d...
// 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
use super::pandas_columns::{ BooleanBlock, BytesBlock, DateTimeBlock, Float64Block, HasPandasColumn, Int64Block, PandasColumn, PandasColumnObject, StringBlock, }; use super::types::{PandasDType, PandasTypeSystem}; use anyhow::anyhow; use connectorx::{ ConnectorAgentError, Consume, DataOrder, Destination, De...
(&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
use super::pandas_columns::{ BooleanBlock, BytesBlock, DateTimeBlock, Float64Block, HasPandasColumn, Int64Block, PandasColumn, PandasColumnObject, StringBlock, }; use super::types::{PandasDType, PandasTypeSystem}; use anyhow::anyhow; use connectorx::{ ConnectorAgentError, Consume, DataOrder, Destination, De...
} 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
// Package towrap wraps two versions of Traffic Ops clients to give up-to-date // information, possibly using legacy API versions. package towrap /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional...
// 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
// Package towrap wraps two versions of Traffic Ops clients to give up-to-date // information, possibly using legacy API versions. package towrap /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional...
return configBytes, err } } hist.Stats = crConfig.Stats if err = s.CRConfigValid(crConfig, cdn); err != nil { err = errors.New("invalid CRConfig: " + err.Error()) hist.Err = err return configBytes, err } s.lastCRConfig.Set(cdn, configBytes, &crConfig.Stats) return configBytes, nil } // LastCRConfig ...
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
// Package towrap wraps two versions of Traffic Ops clients to give up-to-date // information, possibly using legacy API versions. package towrap /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional...
} (*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
// Package towrap wraps two versions of Traffic Ops clients to give up-to-date // information, possibly using legacy API versions. package towrap /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional...
(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
//! CSIS-616 - Program #3 //! //! Some parts were originally made by: Ralph W. Crosby PhD. //! Edited and added to by: Paige Peck //! //! //! Process a yaml format deterministic finite automaton producing //! - A textual representation of the internal state graph //! - A Graphviz `.dot` file representing the graph /...
let stdin = io::stdin(); for line in stdin.lock().lines() { // Get the line out of the Result, should never error let sentence = &line.unwrap(); println!("Processing sentence <{}>", sentence); match self.test_sentence(sentence) { Ok(b) => println!("{}", ...
self) {
identifier_name
main.rs
//! CSIS-616 - Program #3 //! //! Some parts were originally made by: Ralph W. Crosby PhD. //! Edited and added to by: Paige Peck //! //! //! Process a yaml format deterministic finite automaton producing //! - A textual representation of the internal state graph //! - A Graphviz `.dot` file representing the graph /...
//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
//! CSIS-616 - Program #3 //! //! Some parts were originally made by: Ralph W. Crosby PhD. //! Edited and added to by: Paige Peck //! //! //! Process a yaml format deterministic finite automaton producing //! - A textual representation of the internal state graph //! - A Graphviz `.dot` file representing the graph /...
// ********************************************************************* /// 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(&regex); //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
/** * Module Description * * Version Date Author Remarks * 1.00 13 Jul 2014 AnJoe * * 8/2/2014 * Modified to allow geocoding on Booking records */ var paramGeoCodeFormIds = nlapiGetContext().getSetting('SCRIPT', 'custscript_sct246_formids').split(','); var paramGeoCodeSuppli...
} 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
/** * Module Description * * Version Date Author Remarks * 1.00 13 Jul 2014 AnJoe * * 8/2/2014 * Modified to allow geocoding on Booking records */ var paramGeoCodeFormIds = nlapiGetContext().getSetting('SCRIPT', 'custscript_sct246_formids').split(','); var paramGeoCodeSuppli...
(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
/** * Module Description * * Version Date Author Remarks * 1.00 13 Jul 2014 AnJoe * * 8/2/2014 * Modified to allow geocoding on Booking records */ var paramGeoCodeFormIds = nlapiGetContext().getSetting('SCRIPT', 'custscript_sct246_formids').split(','); var paramGeoCodeSuppli...
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
/** * Module Description * * Version Date Author Remarks * 1.00 13 Jul 2014 AnJoe * * 8/2/2014 * Modified to allow geocoding on Booking records */ var paramGeoCodeFormIds = nlapiGetContext().getSetting('SCRIPT', 'custscript_sct246_formids').split(','); var paramGeoCodeSuppli...
/** * 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
//! I2C Peripheral use crate::common::{ Register, Frequency, I2CInterrupt, I2CFlags, I2CBitMode, MasterMode, DutyCycle, DualAddress }; use crate::common::enums::RCCPeripheral; use crate::common::structs::pins::Pin; use embedded_hal::blocking::i2c::{ Read, Write, WriteRead }; use crate::peripherals::extended::{ gpio:...
(&mut self, a: I2CBitMode) -> &mut Self { match a { I2CBitMode::Bit7 => self.clear(2, 15), _ => self.set(2, 15), } } /// Writes the interface address 1 /// To be set **after** the interface bit size is set (7-bit or 10-bit) pub fn set_address_1(&mut self, addr: u32) -> &mut Self { match self.is_set(2, ...
address_mode
identifier_name
i2c.rs
//! I2C Peripheral use crate::common::{ Register, Frequency, I2CInterrupt, I2CFlags, I2CBitMode, MasterMode, DutyCycle, DualAddress }; use crate::common::enums::RCCPeripheral; use crate::common::structs::pins::Pin; use embedded_hal::blocking::i2c::{ Read, Write, WriteRead }; use crate::peripherals::extended::{ gpio:...
/// Clear the given flag /// If the flag is cleared by hardware, it does nothing pub fn clear_flag(&mut self, f: I2CFlags) -> &mut Self { match f.offsets() { (5, o) => match o { 8...15 => self.clear(5, o), _ => self }, _ => self } } /// Set CCR /// Refer to the STM32F4 user manual pub fn...
{ (self.block[6].read() >> 8) & 0b1111_1111 }
identifier_body
i2c.rs
//! I2C Peripheral use crate::common::{ Register, Frequency, I2CInterrupt, I2CFlags, I2CBitMode, MasterMode, DutyCycle, DualAddress }; use crate::common::enums::RCCPeripheral; use crate::common::structs::pins::Pin; use embedded_hal::blocking::i2c::{ Read, Write, WriteRead }; use crate::peripherals::extended::{ gpio:...
// 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
package main import ( "fmt" "io" "log" "math" "math/rand" "os" "path" "sort" "strconv" "time" "github.com/go-errors/errors" "github.com/andyleap/gioframework" "github.com/xarg/gopathfinding" "os/signal" ) const ( TileEmpty = -1 TileMountain = -2 TileFog = -3 TileFogObstacle = -4 ) ...
func Sum(x []int) int { // TODO make this an interface for fun sum := 0 for _, i := range x { sum += i } return sum } func dotProduct(x [2]int, y [2]int) float64 { return float64(x[0]) * float64(y[0]) + float64(x[1]) * float64(y[1]) } // getEnemyCenterOfMass find the central point of the visible enemy terr...
{ return math.Min(math.Max(val, min), max) }
identifier_body
bot.go
package main import ( "fmt" "io" "log" "math" "math/rand" "os" "path" "sort" "strconv" "time" "github.com/go-errors/errors" "github.com/andyleap/gioframework" "github.com/xarg/gopathfinding" "os/signal" ) const ( TileEmpty = -1 TileMountain = -2 TileFog = -3 TileFogObstacle = -4 ) ...
(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
package main import ( "fmt" "io" "log" "math" "math/rand" "os" "path" "sort" "strconv" "time" "github.com/go-errors/errors" "github.com/andyleap/gioframework" "github.com/xarg/gopathfinding" "os/signal" ) const ( TileEmpty = -1 TileMountain = -2 TileFog = -3 TileFogObstacle = -4 ) ...
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
package main import ( "fmt" "io" "log" "math" "math/rand" "os" "path" "sort" "strconv" "time" "github.com/go-errors/errors" "github.com/andyleap/gioframework" "github.com/xarg/gopathfinding" "os/signal" ) const ( TileEmpty = -1 TileMountain = -2 TileFog = -3 TileFogObstacle = -4 ) ...
else { myTeam := game.Teams[game.PlayerIndex] return tile.Faction >= 0 && game.Teams[tile.Faction] != myTeam } } func logSortedScores(scores map[string]float64) { keys := make([]string, len(scores)) i := 0 for k := range scores { keys[i] = k i++ } sort.Strings(keys) for _, k := range keys { log.Pri...
{ // This means we're playing 1v1 or FFA return tile.Faction != game.PlayerIndex && tile.Faction >= 0 }
conditional_block
data_window.go
// Copyright 2021 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
aggregatedSubWindows := 1 // Aggregate later sub windows i++ for i < len(rotatedSubWindows) && aggregatedSubWindows < maxSubWindowLengthInWindow { thisWindow.ExecuteCount += rotatedSubWindows[i].ExecuteCount thisWindow.TiFlashUsage.PushDown += rotatedSubWindows[i].TiFlashUsage.PushDown thisWindow.TiFla...
if i == 0 { startWindow = thisWindow } else { startWindow = *rotatedSubWindows[i-1] }
random_line_split
data_window.go
// Copyright 2021 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
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
// Copyright 2021 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
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
// Copyright 2021 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
(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
use std::collections::{HashMap, HashSet}; use console::style; use dialoguer::Confirm; use fimfic_tracker::{ Config, Id, Result, SensibilityLevel, Story, StoryData, StoryStatus, StoryUpdate, TrackerError, }; use crate::args::{Download, Prompt}; use crate::readable::ReadableDate; use crate::Requester; macro_rules...
StoryDownload::Forced(id) => match story_data.get(id) { Some(story) => requester.download(story)?, None => warn!("{} is not present in the tracker file.", id), }, }; // Insert the update once it downloads. if let StoryDownload::Update(id, ...
// So I throw in a `match` to "safely" unwrap it and throw a warning if it is not // present.
random_line_split
download.rs
use std::collections::{HashMap, HashSet}; use console::style; use dialoguer::Confirm; use fimfic_tracker::{ Config, Id, Result, SensibilityLevel, Story, StoryData, StoryStatus, StoryUpdate, TrackerError, }; use crate::args::{Download, Prompt}; use crate::readable::ReadableDate; use crate::Requester; macro_rules...
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
use std::collections::{HashMap, HashSet}; use console::style; use dialoguer::Confirm; use fimfic_tracker::{ Config, Id, Result, SensibilityLevel, Story, StoryData, StoryStatus, StoryUpdate, TrackerError, }; use crate::args::{Download, Prompt}; use crate::readable::ReadableDate; use crate::Requester; macro_rules...
{ 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
use std::collections::{HashMap, HashSet}; use console::style; use dialoguer::Confirm; use fimfic_tracker::{ Config, Id, Result, SensibilityLevel, Story, StoryData, StoryStatus, StoryUpdate, TrackerError, }; use crate::args::{Download, Prompt}; use crate::readable::ReadableDate; use crate::Requester; macro_rules...
{ 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
//! The ``asnd`` module of ``ogc-rs``. //! //! This module implements a safe wrapper around the audio functions found in ``asndlib.h``. use crate::{ffi, OgcError, Result}; use alloc::format; use core::time::Duration; macro_rules! if_not { ($valid:ident => $error_output:expr, $var:ident $(,)*) => { if $var...
() -> 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
//! The ``asnd`` module of ``ogc-rs``. //! //! This module implements a safe wrapper around the audio functions found in ``asndlib.h``. use crate::{ffi, OgcError, Result}; use alloc::format; use core::time::Duration; macro_rules! if_not { ($valid:ident => $error_output:expr, $var:ident $(,)*) => { if $var...
/// Tests to determine if the voice is ready to receive a new buffer sample /// with `Asnd::add_voice()`. Returns true if voice is ready. pub fn test_voice_buffer_ready(voice: u32) -> bool { assert!(voice < 16, "Voice index {} is >= 16", voice); unsafe { ffi::ASND_TestVoiceBufferReady(voic...
{ assert!(voice < 16, "Voice index {} is >= 16", voice); unsafe { ffi::ASND_TestPointer(voice as i32, pointer as *mut _) } }
identifier_body
asnd.rs
//! The ``asnd`` module of ``ogc-rs``. //! //! This module implements a safe wrapper around the audio functions found in ``asndlib.h``. use crate::{ffi, OgcError, Result}; use alloc::format; use core::time::Duration; macro_rules! if_not { ($valid:ident => $error_output:expr, $var:ident $(,)*) => { if $var...
}
random_line_split
dg.go
package tbk import ( "strconv" ) type dg struct { Client *Tbk } func (t *Tbk) Dg() *dg { return &dg{Client: t} } // 搜索响应数据结构体 type MaterialOptionalResponse struct { Response struct { TotalResults int `json:"total_results"` ResultList struct { MapData []MaterialOptionalData `json:"map_data"` } `json:"...
n:"order_tk_type"` // 订单淘客类型:1.淘客订单 2.非淘客订单,仅淘宝天猫拉新适用 UnionId string `json:"union_id"` MemberId int `json:"member_id"` MemberNick string `json:"member_nick"` SiteId int64 `json:"site_id"` SiteName string `json:"site_name"` AdzoneId int64 ...
`jso
identifier_name
dg.go
package tbk import ( "strconv" ) type dg struct { Client *Tbk } func (t *Tbk) Dg() *dg
// 搜索响应数据结构体 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
package tbk import ( "strconv" ) type dg struct { Client *Tbk } func (t *Tbk) Dg() *dg { return &dg{Client: t} } // 搜索响应数据结构体 type MaterialOptionalResponse struct { Response struct { TotalResults int `json:"total_results"` ResultList struct { MapData []MaterialOptionalData `json:"map_data"` } `json:"...
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
package tbk import ( "strconv" ) type dg struct { Client *Tbk } func (t *Tbk) Dg() *dg { return &dg{Client: t} } // 搜索响应数据结构体 type MaterialOptionalResponse struct { Response struct { TotalResults int `json:"total_results"` ResultList struct { MapData []MaterialOptionalData `json:"map_data"` } `json:"...
conditional_block
path.rs
//! File path utilities. //! //! Some of the functions are similar to [`std::path::Path`] ones, but here they //! work directly upon [`&str`](str) instead of [`&OsStr`](std::ffi::OsStr). use crate::co; use crate::decl::*; use crate::guard::*; use crate::prelude::*; /// Returns an iterator over the files and...
impl<'a> DirWalkIter<'a> { pub(in crate::kernel) fn new(dir_path: String) -> Self { Self { runner: DirListIter::new(dir_path, None), subdir_runner: None, no_more: false, } } }
}, } } }
random_line_split
path.rs
//! File path utilities. //! //! Some of the functions are similar to [`std::path::Path`] ones, but here they //! work directly upon [`&str`](str) instead of [`&OsStr`](std::ffi::OsStr). use crate::co; use crate::decl::*; use crate::guard::*; use crate::prelude::*; /// Returns an iterator over the files and...
/// 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
//! File path utilities. //! //! Some of the functions are similar to [`std::path::Path`] ones, but here they //! work directly upon [`&str`](str) instead of [`&OsStr`](std::ffi::OsStr). use crate::co; use crate::decl::*; use crate::guard::*; use crate::prelude::*; /// Returns an iterator over the files and...
match &mut self.subdir_runner { None => { let cur_file = self.runner.next(); match cur_file { None => None, Some(cur_file) => { match cur_file { Err(e) => { self.no_more = true; // prevent further iterations Some(Err(e)) }, Ok(cur_file) =>...
{ return None; }
conditional_block
path.rs
//! File path utilities. //! //! Some of the functions are similar to [`std::path::Path`] ones, but here they //! work directly upon [`&str`](str) instead of [`&OsStr`](std::ffi::OsStr). use crate::co; use crate::decl::*; use crate::guard::*; use crate::prelude::*; /// Returns an iterator over the files and...
(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
""" Copyright (c) 2014 Russell Nakamura Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribut...
(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
""" Copyright (c) 2014 Russell Nakamura Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribut...
@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
""" Copyright (c) 2014 Russell Nakamura Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribut...
# 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
""" Copyright (c) 2014 Russell Nakamura Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribut...
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
# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions a...
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
# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions a...
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
# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions a...
t = timeit.Timer(stmt) time = t.timeit(1) print('Time to run timeloop = ', time) # Move timeloop output files to the right directory for f in output_file_names: if os.path.exists(f): os.rename(f, dirname + '/' + f)
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
# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions a...
(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
""""" GBDX Notebook: "Identifying Destroyed Buildings with Multispectral Imagery" Link: https://notebooks.geobigdata.io/hub/notebooks/5b47cfb82486966ea89b75fd?tab=code Author: Ai-Linh Alten Date created: 7/5/2018 Date last modified: 7/13/2018 Python Version: 2.7.15 """ import cPickle import fo...
(array, subplot_ijk, title="", font_size=18, cmap=None): """Plot image with subplot. Requires image and subplot location (ie. (1,2,1)). You can also set title.""" sp = plt.subplot(*subplot_ijk) sp.set_title(title, fontsize=font_size) plt.axis('off') plt.imshow(array, cmap=cmap) def display...
plot_array
identifier_name
ops.py
""""" GBDX Notebook: "Identifying Destroyed Buildings with Multispectral Imagery" Link: https://notebooks.geobigdata.io/hub/notebooks/5b47cfb82486966ea89b75fd?tab=code Author: Ai-Linh Alten Date created: 7/5/2018 Date last modified: 7/13/2018 Python Version: 2.7.15 """ import cPickle import fo...
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
""""" GBDX Notebook: "Identifying Destroyed Buildings with Multispectral Imagery" Link: https://notebooks.geobigdata.io/hub/notebooks/5b47cfb82486966ea89b75fd?tab=code Author: Ai-Linh Alten Date created: 7/5/2018 Date last modified: 7/13/2018 Python Version: 2.7.15 """ import cPickle import fo...
def geojson_to_polygons_groundtruth(js_): """Convert geojson to polygons for the groundtruth map.""" burnt_polys = [] building_polys = [] for i, feat in enumerate(js_['features']): o = { "coordinates": feat['geometry']['coordinates'], "type": feat['geometry']['type']...
"""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
""""" GBDX Notebook: "Identifying Destroyed Buildings with Multispectral Imagery" Link: https://notebooks.geobigdata.io/hub/notebooks/5b47cfb82486966ea89b75fd?tab=code Author: Ai-Linh Alten Date created: 7/5/2018 Date last modified: 7/13/2018 Python Version: 2.7.15 """ import cPickle import fo...
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
# -*- coding: utf-8 -*- """ Created on Sat Aug 11 13:13:53 2018 @author: zhang """ ''' Warp Commands use during diffusion-weighted images preprocessing ================================================================ dwidenoise & mrdegibbs from MRTrix3.0; eddy-openmp from FSL ------------------------------------------...
def _num_threads_update(self): self._num_threads = self.inputs.num_threads if not isdefined(self.inputs.num_threads): if 'OMP_NUM_THREADS' in self.inputs.environ: del self.inputs.environ['OMP_NUM_THREADS'] else: self.inputs.environ['OMP_NUM_THREADS']...
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
# -*- coding: utf-8 -*- """ Created on Sat Aug 11 13:13:53 2018 @author: zhang """ ''' Warp Commands use during diffusion-weighted images preprocessing ================================================================ dwidenoise & mrdegibbs from MRTrix3.0; eddy-openmp from FSL ------------------------------------------...
if os.path.exists(out_outlier_report): outputs['out_outlier_report'] = out_outlier_report return outputs
outputs['out_shell_alignment_parameters'] = \ out_shell_alignment_parameters
conditional_block
dwi_corr_util.py
# -*- coding: utf-8 -*- """ Created on Sat Aug 11 13:13:53 2018 @author: zhang """ ''' Warp Commands use during diffusion-weighted images preprocessing ================================================================ dwidenoise & mrdegibbs from MRTrix3.0; eddy-openmp from FSL ------------------------------------------...
if 'OMP_NUM_THREADS' in self.inputs.environ: del self.inputs.environ['OMP_NUM_THREADS'] else: self.inputs.environ['OMP_NUM_THREADS'] = str( self.inputs.num_threads) def _use_cuda(self): self._cmd = 'eddy_cuda' if self.inputs.use_cuda else 'edd...
self._num_threads = self.inputs.num_threads if not isdefined(self.inputs.num_threads):
random_line_split
dwi_corr_util.py
# -*- coding: utf-8 -*- """ Created on Sat Aug 11 13:13:53 2018 @author: zhang """ ''' Warp Commands use during diffusion-weighted images preprocessing ================================================================ dwidenoise & mrdegibbs from MRTrix3.0; eddy-openmp from FSL ------------------------------------------...
(self): self._num_threads = self.inputs.num_threads if not isdefined(self.inputs.num_threads): if 'OMP_NUM_THREADS' in self.inputs.environ: del self.inputs.environ['OMP_NUM_THREADS'] else: self.inputs.environ['OMP_NUM_THREADS'] = str( self....
_num_threads_update
identifier_name
lib.rs
//! [![GitHub time-rs/time](https://img.shields.io/badge/GitHub-time--rs%2Ftime-9b88bb?logo=github&style=for-the-badge)](https://github.com/time-rs/time) //! ![license MIT or Apache-2.0](https://img.shields.io/badge/license-MIT%20or%20Apache--2.0-779a6b?style=for-the-badge) //! [![minimum rustc 1.40.0](https://img.shie...
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
package stanmsg import ( "context" "fmt" "sync" "time" "github.com/huangjunwen/golibs/logr" "github.com/huangjunwen/golibs/taskrunner" "github.com/huangjunwen/golibs/taskrunner/limitedrunner" "github.com/nats-io/nats.go" "github.com/nats-io/stan.go" "github.com/rs/xid" "google.golang.org/protobuf/proto" ...
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
package stanmsg import ( "context" "fmt" "sync" "time" "github.com/huangjunwen/golibs/logr" "github.com/huangjunwen/golibs/taskrunner" "github.com/huangjunwen/golibs/taskrunner/limitedrunner" "github.com/nats-io/nats.go" "github.com/nats-io/stan.go" "github.com/rs/xid" "google.golang.org/protobuf/proto" ...
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
package stanmsg import ( "context" "fmt" "sync" "time" "github.com/huangjunwen/golibs/logr" "github.com/huangjunwen/golibs/taskrunner" "github.com/huangjunwen/golibs/taskrunner/limitedrunner" "github.com/nats-io/nats.go" "github.com/nats-io/stan.go" "github.com/rs/xid" "google.golang.org/protobuf/proto" ...
{ 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
package stanmsg import ( "context" "fmt" "sync" "time" "github.com/huangjunwen/golibs/logr" "github.com/huangjunwen/golibs/taskrunner" "github.com/huangjunwen/golibs/taskrunner/limitedrunner" "github.com/nats-io/nats.go" "github.com/nats-io/stan.go" "github.com/rs/xid" "google.golang.org/protobuf/proto" ...
(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
#! /usr/bin/python """ circuitpusher utilizes floodlight rest APIs to create a bidirectional circuit, i.e., permanent flow entry, on all switches in route between two devices based on IP addresses with specified priority. Notes: 1. The circuit pusher currently only creates circuit with two IP end points 2. Prior...
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
#! /usr/bin/python """ circuitpusher utilizes floodlight rest APIs to create a bidirectional circuit, i.e., permanent flow entry, on all switches in route between two devices based on IP addresses with specified priority. Notes: 1. The circuit pusher currently only creates circuit with two IP end points 2. Prior...
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
use ndarray::Array2; use rand::Rng; use std::borrow::Borrow; use std::cmp::Ordering; use std::collections::{BinaryHeap, HashMap, HashSet, VecDeque}; use std::fmt::{Display, Formatter}; pub const WIDTH: usize = 4; pub const HEIGHT: usize = 4; #[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)] pub struct Board([[u8; WI...
; 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
use ndarray::Array2; use rand::Rng; use std::borrow::Borrow; use std::cmp::Ordering; use std::collections::{BinaryHeap, HashMap, HashSet, VecDeque}; use std::fmt::{Display, Formatter}; pub const WIDTH: usize = 4; pub const HEIGHT: usize = 4; #[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)] pub struct Board([[u8; WI...
#[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
use ndarray::Array2; use rand::Rng; use std::borrow::Borrow; use std::cmp::Ordering; use std::collections::{BinaryHeap, HashMap, HashSet, VecDeque}; use std::fmt::{Display, Formatter}; pub const WIDTH: usize = 4; pub const HEIGHT: usize = 4; #[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)] pub struct Board([[u8; WI...
// .indexed_iter() // .map(|((x, y), v)| { // let (w, h) = self.0.current_board().size(); // let (ox, oy) = if *v == 0 { // (w - 1, h - 1) // } else { // let v = (*v - 1) as usize; // (v %...
random_line_split
code_quality_eval.py
import sys import os sys.path.insert(0, '../oscar.py') import re from oscar import Project from oscar import Time_project_info as Proj import subprocess from time import time as current_time start_time = current_time() def bash(command): proc = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True) (out, er...
(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
import sys import os sys.path.insert(0, '../oscar.py') import re from oscar import Project from oscar import Time_project_info as Proj import subprocess from time import time as current_time start_time = current_time() def bash(command): proc = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True) (out, er...
#### 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
import sys import os sys.path.insert(0, '../oscar.py') import re from oscar import Project from oscar import Time_project_info as Proj import subprocess from time import time as current_time start_time = current_time() def bash(command): proc = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True) (out, er...
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
import sys import os sys.path.insert(0, '../oscar.py') import re from oscar import Project from oscar import Time_project_info as Proj import subprocess from time import time as current_time start_time = current_time() def bash(command): proc = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True) (out, er...
# 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
# coding: utf-8 """ Generate figures that will go on my AAS poster """ from __future__ import division # Standard library import sys import os import cPickle as pickle # Third-party #import apwlib.convert as c import apwlib.geometry as g import matplotlib matplotlib.use("WxAgg") import numpy as np import matplotl...
# http://kanaloa.ipac.caltech.edu/ibe/search/ptf/dev/process?POS=129.568,19.6232 # one http://kanaloa.ipac.caltech.edu/ibe/data/ptf/dev/process/proc/2010/05/15/f2/c6/p13/v1/PTF_201005152355_i_p_scie_t053906_u011486277_f02_p110004_c06.fits?center=129.568,19.6232deg&size=150px # two http://kanaloa.ipac.caltec...
def systematics_9347():
random_line_split
aas220_poster.py
# coding: utf-8 """ Generate figures that will go on my AAS poster """ from __future__ import division # Standard library import sys import os import cPickle as pickle # Third-party #import apwlib.convert as c import apwlib.geometry as g import matplotlib matplotlib.use("WxAgg") import numpy as np import matplotl...
# To be used by the Praesepe timescale distribution plot and the # detection efficiency timescale_bins = np.logspace(np.log10(1), np.log10(1000), 100) # from 1 day to 1000 days def praesepe_timescale_distribution(): filename = "data/praesepeTimeScales.npy" timescales = np.load(filename) plt....
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
# coding: utf-8 """ Generate figures that will go on my AAS poster """ from __future__ import division # Standard library import sys import os import cPickle as pickle # Third-party #import apwlib.convert as c import apwlib.geometry as g import matplotlib matplotlib.use("WxAgg") import numpy as np import matplotl...
(): import PraesepeLightCurves as plc # TODO: Sample timescale from the distribution that Amanda will send me # TODO: Fix legend in post-editing plc.aas_figure() def variability_indices_detection_efficiency(): """ This figure should show the detection efficiency curve for the Praesepe data...
variability_indices
identifier_name
aas220_poster.py
# coding: utf-8 """ Generate figures that will go on my AAS poster """ from __future__ import division # Standard library import sys import os import cPickle as pickle # Third-party #import apwlib.convert as c import apwlib.geometry as g import matplotlib matplotlib.use("WxAgg") import numpy as np import matplotl...
f = open("data/aas_survey_detection_efficiency.pickle", "r") data_dict = pickle.load(f) # Plotting stuff plt.figure(figsize=(15,15)) dcs_cutoff = 300. num_observations = [2**x for x in range(int(np.log2(max_num_observations)), int(np.log2(min_num_observations))-1, -1)] linestyles ...
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
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #extract models info from unifi javascript # N Waterton 4th July 2019 V1.0: initial release # N Waterton 13th July 2019 V1.0.2 minor fixes. # N Waterton 10th Sep 2019 V1.0.3 minor fixes import time, os, sys, json, re from datetime import timedelta from collections import...
standard = [x for x in range(len(ports))] if ports.get('standard'): standard = ports_list_decode(ports['standard']) if ports.get('sfp'): sfp = ports_list_decode(ports['sfp']) if ports.get('plus'): sfp_plus = ports_list_decode(ports['plus']) return standard, sfp, sfp_plus...
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
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #extract models info from unifi javascript # N Waterton 4th July 2019 V1.0: initial release # N Waterton 13th July 2019 V1.0.2 minor fixes. # N Waterton 10th Sep 2019 V1.0.3 minor fixes import time, os, sys, json, re from datetime import timedelta from collections import...
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
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #extract models info from unifi javascript # N Waterton 4th July 2019 V1.0: initial release # N Waterton 13th July 2019 V1.0.2 minor fixes. # N Waterton 10th Sep 2019 V1.0.3 minor fixes import time, os, sys, json, re from datetime import timedelta from collections import...
''' Main routine ''' global log import argparse parser = argparse.ArgumentParser(description='extract model info from Unifi') parser.add_argument('-f','--files', action="store", default='/usr/lib/unifi', help='unifi files base location (default: /usr/lib/unifi)') parser.add_argument('-u'...
():
identifier_name
get_models.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #extract models info from unifi javascript # N Waterton 4th July 2019 V1.0: initial release # N Waterton 13th July 2019 V1.0.2 minor fixes. # N Waterton 10th Sep 2019 V1.0.3 minor fixes import time, os, sys, json, re from datetime import timedelta from collections import...
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
use webhdfs::*; fn main() { use std::fs::File; use std::path::Path; use std::fs::create_dir_all; use commandline::*; let (mut client, op) = parse_command_line(); match op { Operation::Get(mut fs) => { match &fs[..] { &[ref input] => { let...
}; (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
use webhdfs::*; fn main() { use std::fs::File; use std::path::Path; use std::fs::create_dir_all; use commandline::*; let (mut client, op) = parse_command_line(); match op { Operation::Get(mut fs) => { match &fs[..] { &[ref input] => { let...
} #[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
use webhdfs::*; fn main() { use std::fs::File; use std::path::Path; use std::fs::create_dir_all; use commandline::*; let (mut client, op) = parse_command_line(); match op { Operation::Get(mut fs) => { match &fs[..] { &[ref input] => { let...
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
use webhdfs::*; fn main() { use std::fs::File; use std::path::Path; use std::fs::create_dir_all; use commandline::*; let (mut client, op) = parse_command_line(); match op { Operation::Get(mut fs) => { match &fs[..] { &[ref input] => { let...
() -> ! { 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
/* Copyright 2021 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, ...
(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
/* Copyright 2021 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, ...
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
/* Copyright 2021 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, ...
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
/* Copyright 2021 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, ...
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
package server import ( "avrilko-rpc/log" "avrilko-rpc/protocol" "avrilko-rpc/share" "bufio" "context" "crypto/tls" "errors" "fmt" "io" "net" "net/http" "os" "os/signal" "reflect" "runtime" "strings" "sync" "sync/atomic" "syscall" "time" ) var ErrServerClosed = errors.New("主服务已经关闭") const ( Read...
var err error response := request.Clone() response.SetMessageType(protocol.Response) serviceName := request.ServicePath methodName := request.ServiceMethod s.serviceMapMu.RLock() service, ok := s.serviceMap[serviceName] s.serviceMapMu.RUnlock() if !ok { // 都没注册直接返回错误 err = errors.New(fmt.Sprintf("不能找到服务发现...
的 func (s *Server) handleRequestForFunction(ctx context.Context, request *protocol.Message) (*protocol.Message, error) {
conditional_block
server.go
package server import ( "avrilko-rpc/log" "avrilko-rpc/protocol" "avrilko-rpc/share" "bufio" "context" "crypto/tls" "errors" "fmt" "io" "net" "net/http" "os" "os/signal" "reflect" "runtime" "strings" "sync" "sync/atomic" "syscall" "time" ) var ErrServerClosed = errors.New("主服务已经关闭") const ( Read...
requestType, err = s.Plugins.DoPreCall(ctx, serviceName, methodName, requestType) if err != nil { return handleError(response, err) } if funcType.requestType.Kind() != reflect.Ptr { // 不是指针 err = service.callForFunc(ctx, funcType, reflect.ValueOf(requestType).Elem(), reflect.ValueOf(responseType)) } else { ...
defer ObjectPool.Put(funcType.responseType, responseType)
random_line_split
server.go
package server import ( "avrilko-rpc/log" "avrilko-rpc/protocol" "avrilko-rpc/share" "bufio" "context" "crypto/tls" "errors" "fmt" "io" "net" "net/http" "os" "os/signal" "reflect" "runtime" "strings" "sync" "sync/atomic" "syscall" "time" ) var ErrServerClosed = errors.New("主服务已经关闭") const ( Read...
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
package server import ( "avrilko-rpc/log" "avrilko-rpc/protocol" "avrilko-rpc/share" "bufio" "context" "crypto/tls" "errors" "fmt" "io" "net" "net/http" "os" "os/signal" "reflect" "runtime" "strings" "sync" "sync/atomic" "syscall" "time" ) var ErrServerClosed = errors.New("主服务已经关闭") const ( Read...
identifier_body
prefilter.rs
use core::{ cmp, fmt::Debug, panic::{RefUnwindSafe, UnwindSafe}, u8, }; use alloc::{sync::Arc, vec, vec::Vec}; use crate::{ packed, util::{ alphabet::ByteSet, search::{Match, MatchKind, Span}, }, }; /// A prefilter for accelerating a search. /// /// This crate uses prefilt...
{ /// 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
use core::{ cmp, fmt::Debug, panic::{RefUnwindSafe, UnwindSafe}, u8, }; use alloc::{sync::Arc, vec, vec::Vec}; use crate::{ packed, util::{ alphabet::ByteSet, search::{Match, MatchKind, Span}, }, }; /// A prefilter for accelerating a search. /// /// This crate uses prefilt...
} } /// A prefilter for scanning for a single "rare" byte. #[cfg(feature = "perf-literal")] #[derive(Clone, Debug)] struct RareBytesOne { byte1: u8, offset: RareByteOffset, } #[cfg(feature = "perf-literal")] impl PrefilterI for RareBytesOne { fn find_in(&self, haystack: &[u8], span: Span) -> Candidat...
{ self.rare_set.add(byte); self.count += 1; self.rank_sum += freq_rank(byte) as u16; }
conditional_block
prefilter.rs
use core::{ cmp, fmt::Debug, panic::{RefUnwindSafe, UnwindSafe}, u8, }; use alloc::{sync::Arc, vec, vec::Vec}; use crate::{ packed, util::{ alphabet::ByteSet, search::{Match, MatchKind, Span}, }, }; /// A prefilter for accelerating a search. /// /// This crate uses prefilt...
} /// 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
use core::{ cmp, fmt::Debug, panic::{RefUnwindSafe, UnwindSafe}, u8, }; use alloc::{sync::Arc, vec, vec::Vec}; use crate::{ packed, util::{ alphabet::ByteSet, search::{Match, MatchKind, Span}, }, }; /// A prefilter for accelerating a search. /// /// This crate uses prefilt...
for b in 0..=255 { if builder.rare_set.contains(b) { bytes[len] = b as u8; len += 1; } } let finder: Arc<dyn PrefilterI> = match len { 0 => return None, 1 => Arc::new(RareBytesOne ...
} let (mut bytes, mut len) = ([0; 3], 0);
random_line_split
code.go
/* Copyright 2022 The Vitess Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, soft...
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
/* Copyright 2022 The Vitess Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, soft...
func errorWithState(id string, code vtrpcpb.Code, state State, short, long string) func(args ...any) *VitessError { return func(args ...any) *VitessError { return &VitessError{ Err: NewErrorf(code, state, id+": "+short, args...), Description: long, ID: id, State: state, } } }
{ 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
/* Copyright 2022 The Vitess Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, soft...
return &VitessError{ Err: New(code, id+": "+s), Description: long, ID: id, } } } func errorWithState(id string, code vtrpcpb.Code, state State, short, long string) func(args ...any) *VitessError { return func(args ...any) *VitessError { return &VitessError{ Err: NewErrorf...
{ s = fmt.Sprintf(s, args...) }
conditional_block