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 |
|---|---|---|---|---|
BratsCRFNeighborWhole.py | Counter
from CRFUtils import *
from BratsCheckPredictions import *
import math
from math import *
train_path="/media/bmi/MyPassport/new_n4/Recon_2013_data/N4_zscore_training_t1_t1c_hist_match"
test_path="/media/bmi/MyPassport/new_n4/Recon_2013_data/N4_zscore_testing_t1_t1c_hist_match"
#train_path="/media/bmi/MyPa... | [trainLayers,trainTruth,sliceShape] = train
print "Training slices loaded in %f" % (train_load_time)
n_features= len(trainLayers[0][0,0])
print "Layer shape is : "
print trainLayers[0].shape
print "Training the model"
edges= np.load("/home/bmi/CRF/edges/"+edges+".npy")
G =... | padding=(30,30,30,30)
if directed==True:
features +="+directed"
resultsDir = os.getcwd()+'/CRFResults'
nameLen = len(os.listdir(resultsDir))
edgeFeature = edges
filename=str(nameLen)+"_CRF_iter_"+str(num_iter)+"_"+inference+"_"+trainer+"_"+features+"_"+str(num_train)+"_"+s... | identifier_body |
BratsCRFNeighborWhole.py | Counter
from CRFUtils import *
from BratsCheckPredictions import *
import math
from math import *
train_path="/media/bmi/MyPassport/new_n4/Recon_2013_data/N4_zscore_training_t1_t1c_hist_match"
test_path="/media/bmi/MyPassport/new_n4/Recon_2013_data/N4_zscore_testing_t1_t1c_hist_match"
#train_path="/media/bmi/MyPa... | (num_iter=5,inference="qpbo",trainer="NSlack",num_train=2,num_test=1,C=0.1,edges="180x180_dist1_diag0",inputs=[1,1,1,1,1,1],features="post+img+pred",neighbor=-1,directed=False,savePred=False):
padding=(30,30,30,30)
if directed==True:
features +="+directed"
resultsDir = o... | trainModel_Neighbor | identifier_name |
BratsCRFNeighborWhole.py | Counter
from CRFUtils import *
from BratsCheckPredictions import *
import math
from math import *
train_path="/media/bmi/MyPassport/new_n4/Recon_2013_data/N4_zscore_training_t1_t1c_hist_match"
test_path="/media/bmi/MyPassport/new_n4/Recon_2013_data/N4_zscore_testing_t1_t1c_hist_match"
#train_path="/media/bmi/MyPa... |
if trainer=="Frank":
svm = FrankWolfeSSVM(model = crf,max_iter=num_iter,C=C,n_jobs=6,verbose=1)
elif trainer=="NSlack":
svm = NSlackSSVM(model = crf,max_iter=num_iter,C=C,n_jobs=-1,verbose=1)
else:
svm = OneSlackSSVM(model = crf,max_iter=num_iter,C=C,n_jobs=-1,verbose=1)
... | crf = GraphCRF(inference_method=inference,directed=directed) | conditional_block |
playlist.py | .get('placement_filter')
## audio settings ##
# true if content responds to audio input
self.sound_reactive = kwargs.get('sound_reactive', False)
# if sound_reactive, false if content can still be shown without audio input available
self.sound_required = kwargs.get('sound_requir... |
def game_content(rom):
try:
args = launch.launch_emulator(rom)
except:
return None
name = os.path.splitext(os.path.relpath(os.path.abspath(rom), settings.roms_path))[0]
return Content('screencast', name, cmdline=args['cmd'], params=args.get('params', {}), stretch_aspect=True, has_audio... | import animations
class ProjectMNextPatternAction(animations.Parameter):
def param_def(self):
return {
'name': 'next pattern',
'isAction': True,
}
def handle_input_event(self, type, val):
if type != 'press':
return
... | identifier_body |
playlist.py | .get('placement_filter')
## audio settings ##
# true if content responds to audio input
self.sound_reactive = kwargs.get('sound_reactive', False)
# if sound_reactive, false if content can still be shown without audio input available
self.sound_required = kwargs.get('sound_requir... | Content('kaleidoscope', geometries=['lsdome'], placement_filter=pixel_exact, params={'scale': 2.}),
Content('kaleidoscope', geometries=['prometheus'], params={'scale': 3.2}),
Content('imgkaleidoscope', 'hearts', geometries=['lsdome'], placement_filter=pixel_exact, params={
... | Content('stream', 'hdmi-in', manual=True, stretch_aspect=True, params={
'camera': 'FHD Capture: FHD Capture',
}),
| random_line_split |
playlist.py | kwargs.get('placement_filter')
## audio settings ##
# true if content responds to audio input
self.sound_reactive = kwargs.get('sound_reactive', False)
# if sound_reactive, false if content can still be shown without audio input available
self.sound_required = kwargs.get('sound... | ),
Content('stream', 'hdmi-in', manual=True, stretch_aspect=True, params={
'camera': 'FHD Capture: FHD Capture',
}),
Content('kaleidoscope', geometries=['lsdome'], placement_filter=pixel_exact, params={'scale': 2.}),
Content('kaleidoscope', ge... | _all_content = [
Content('black', '[util] black (note: keeps running and using cpu)', manual=True),
Content('gridtest', '[util] uvw grid test', geometries=['lsdome'], manual=True),
Content('fctest', '[util] fc topology test', params={'fcconfig': fadecandy_config()}),
Cont... | conditional_block |
playlist.py | sdome, and achieves the same spirit for prometheus (which
# doesn't have a concept of 'pixel exact') while still allowing for some variation in wing overlap
return getattr(p, 'rot', 0) == 0 and p.is_1to1
# like pixel_exact, but stretch to fit full canvas (so not 'exact', but still 'aligned')
def align_but_stret... | parse_entry | identifier_name | |
rcu.rs | let (valid, pr) = match pllclk {
48_000_000 => (true, 0b01), // pllclk / 1
72_000_000 => (true, 0b00), // pllclk / 1.5
96_000_000 => (true, 0b11), // pllclk / 2
_ => (false, 0),
};
usbclk_valid = valid;
// Configure US... | }
bus_enable!(CRC => (ahben, crcen));
bus_enable!(DMA0 => (ahben, dma0en)); | random_line_split | |
rcu.rs | clk => (0b01, false),
(None, sysclk) if IRC8M == sysclk => (0b00, false),
_ => (0b10, true),
};
let pllsel_bit;
let predv0_bits;
let pllmf_bits;
if use_pll {
let pllmf;
if let Some(hxtal_freq) = self.hxtal {
// Use... |
/// Returns the frequency of the TIMER1..6 base clock
pub fn timerx(&self) -> Hertz {
let pclk1 = self.pclk1();
if self.apb1_psc == 1 {
pclk1
} else {
Hertz(pclk1.0 * 2)
}
}
/// Returns whether the USBCLK clock frequency is valid for the USB per... | {
let pclk2 = self.pclk2();
if self.apb2_psc == 1 {
pclk2
} else {
Hertz(pclk2.0 * 2)
}
} | identifier_body |
rcu.rs | clk => (0b01, false),
(None, sysclk) if IRC8M == sysclk => (0b00, false),
_ => (0b10, true),
};
let pllsel_bit;
let predv0_bits;
let pllmf_bits;
if use_pll {
let pllmf;
if let Some(hxtal_freq) = self.hxtal {
// Use... | (&self) -> Hertz {
Hertz(self.sysclk.0 / 4)
}
/// Returns the frequency of the TIMER0 base clock
pub fn timer0(&self) -> Hertz {
let pclk2 = self.pclk2();
if self.apb2_psc == 1 {
pclk2
} else {
Hertz(pclk2.0 * 2)
}
}
/// Returns the f... | systick | identifier_name |
rcu.rs | clk => (0b01, false),
(None, sysclk) if IRC8M == sysclk => (0b00, false),
_ => (0b10, true),
};
let pllsel_bit;
let predv0_bits;
let pllmf_bits;
if use_pll | }
}
None
};
let (d, m) = calculate_pll(hxtal_freq, target_sysclk).expect("invalid sysclk value");
predv0_bits = d - 1;
pllmf = m;
} else {
// IRC8M/2 is used as an... | {
let pllmf;
if let Some(hxtal_freq) = self.hxtal {
// Use external clock + divider
pllsel_bit = true;
let calculate_pll = |source: u32, target: u32| -> Option<(u8, u8)> {
const PLL_IN_MIN: u32 = 600_000;
l... | conditional_block |
types.go | nil {
reg.participantsByGaiaID = make(map[string]*ParticipantData)
}
reg.participantsByGaiaID[id] = data
}
if id := data.ID.ChatID; id != "" {
if reg.participantsByChatID == nil {
reg.participantsByChatID = make(map[string]*ParticipantData)
}
reg.participantsByChatID[id] = data
}
reg.allParticipant... |
// Matches returns true if pid's Gaia or Chat ID are both populated and match
// the equivalent values in other.
func (pid *ParticipantID) Matches(other *ParticipantID) bool {
if pid.GaiaID != "" && pid.GaiaID == other.GaiaID {
return true
}
if pid.ChatID != "" && pid.ChatID == other.ChatID {
return true
}
r... | {
return fmt.Sprintf("gaia:%s/chat:%s", pid.GaiaID, pid.ChatID)
} | identifier_body |
types.go | nil {
reg.participantsByGaiaID = make(map[string]*ParticipantData)
}
reg.participantsByGaiaID[id] = data
}
if id := data.ID.ChatID; id != "" {
if reg.participantsByChatID == nil {
reg.participantsByChatID = make(map[string]*ParticipantData)
}
reg.participantsByChatID[id] = data
}
reg.allParticipant... | () string {
if pp := ei.PlusPhoto; pp != nil {
return fmt.Sprintf("%s:%s", pp.AlbumID, pp.PhotoID)
}
if p := ei.ThingV2; p != nil {
// Use a hash of the Thing's URL.
return util.HashForKey(p.URL)
}
return ei.ID
}
type MessageContentAttachment struct {
EmbedItem *EmbedItem `json:"embed_item"`
ID str... | Key | identifier_name |
types.go | nil {
reg.participantsByGaiaID = make(map[string]*ParticipantData)
}
reg.participantsByGaiaID[id] = data
}
if id := data.ID.ChatID; id != "" {
if reg.participantsByChatID == nil {
reg.participantsByChatID = make(map[string]*ParticipantData)
}
reg.participantsByChatID[id] = data
}
reg.allParticipant... |
return ce.decodedEvents[i], nil
}
type ConversationEntry struct {
ConversationInfo *ConversationInfo `json:"conversation"`
}
type SingleID struct {
ID string `json:"id"`
}
type ConversationInfo struct {
ID *SingleID `json:"id"`
Type string `json:"type"`
Name ... | {
var event Event
if err := json.Unmarshal(ce.events[i], &event); err != nil {
return nil, err
}
ce.decodedEvents[i] = &event
} | conditional_block |
types.go | nil {
reg.participantsByGaiaID = make(map[string]*ParticipantData)
}
reg.participantsByGaiaID[id] = data
}
if id := data.ID.ChatID; id != "" {
if reg.participantsByChatID == nil {
reg.participantsByChatID = make(map[string]*ParticipantData)
}
reg.participantsByChatID[id] = data
}
reg.allParticipant... |
type MessageContent struct {
Segment []*MessageContentSegment `json:"segment"`
Attachment []*MessageContentAttachment `json:"attachment"`
}
type ChatMessage struct {
MessageContent *MessageContent `json:"message_content"`
}
type ConversationRename struct {
NewName string `json:"new_name"`
OldName string `... | ID string `json:"id"`
} | random_line_split |
lib.rs | /// assert_eq!( select1(0, 0x0000_0000_0000_0002), Some(1) );
/// assert_eq!( select1(0, 0x0000_0000_0000_0004), Some(2) );
/// assert_eq!( select1(2, 0x0000_0000_0000_0004), None );
/// assert_eq!( select1(2, 0x0000_1010_1010_0114), Some(8) );
/// assert_eq!( select1(3, 0x0000_1010_1010_0114), Some(20) );
/// assert_e... | random_line_split | ||
lib.rs | : u64) -> TestResult {
if r > 64 { return TestResult::discard(); }
TestResult::from_bool(
select1(r as usize, x) == select1_slow(r as usize, x))
}
quickcheck! {
fn select1_prop(r: u8, x: u64) -> TestResult {
select1_prop_base(r, x)
}
fn select1_... | as u64) << 56)
| ((b as u64) << 48)
| ((c as u64) << 40)
| ((d as u64) << 32)
| ((e as u64) << 24)
| ((f as u64) << 16)
| ((g as u64) << 8)
| (h as u64)
}
fn i(a: | identifier_body | |
lib.rs | /// Uses the broadword algorithm from Vigna.
/// Note that bits are numbered from least-significant to most.
///
/// # Examples
///
/// ```
/// use broadword::select1;
///
/// assert_eq!( select1(0, 0x0000_0000_0000_0000), None );
/// assert_eq!( select1(0, 0x0000_0000_0000_0001), Some(0) );
/// assert_eq!( select1(0, ... | ssert_eq!(64, count_ones(0xFFFF_FFFF_FFFF_FFFF));
}
fn count_ones_prop_base(word: u64) -> bool {
count_ones(word) == word.count_ones() as usize
}
quickcheck! {
fn count_ones_prop(word: u64) -> bool {
count_ones_prop_base(word)
}
fn count_ones_prop_hash(word... | f_ffff_ffff_ffff() {
a | identifier_name |
lib.rs | /// Uses the broadword algorithm from Vigna.
/// Note that bits are numbered from least-significant to most.
///
/// # Examples
///
/// ```
/// use broadword::select1;
///
/// assert_eq!( select1(0, 0x0000_0000_0000_0000), None );
/// assert_eq!( select1(0, 0x0000_0000_0000_0001), Some(0) );
/// assert_eq!( select1(0, ... | nds the index of the `r`th one bit in `x`, returning 72 when not found.
///
/// Branchless. Uses the broadword algorithm from Vigna.
/// Note that bits are numbered from least-significant to most.
#[inline]
#[allow(clippy::many_single_char_names)]
pub fn select1_raw(r: usize, x: u64) -> usize {
let r = r as u64;
... | lt)}
}
/// Fi | conditional_block |
uart.rs | _rxto: ReadWrite<u32, Event::Register>, // 0x144-0x148
_reserved7: [u32; 1], // 0x148-0x14C
pub event_rxstarted: ReadWrite<u32, Event::Register>, // 0x14C-0x150
pub event_txstarted: ReadWrite<u32, Event::Register>, // 0x150-0x154
_reserved8: [u32; 1], ... | {
regs: *const UarteRegisters,
client: Cell<Option<&'static kernel::hil::uart::Client>>,
buffer: kernel::common::take_cell::TakeCell<'static, [u8]>,
remaining_bytes: Cell<usize>,
offset: Cell<usize>,
}
#[derive(Copy, Clone)]
pub struct UARTParams {
pub baud_rate: u32,
}
/// UARTE0 handle
// T... | Uarte | identifier_name |
uart.rs | event_rxto: ReadWrite<u32, Event::Register>, // 0x144-0x148
_reserved7: [u32; 1], // 0x148-0x14C
pub event_rxstarted: ReadWrite<u32, Event::Register>, // 0x14C-0x150
pub event_txstarted: ReadWrite<u32, Event::Register>, // 0x150-0x154
_reserved8: [u32; 1], ... | pub pselrts: ReadWrite<u32, Psel::Register>, // 0x508-0x50c
pub pseltxd: ReadWrite<u32, Psel::Register>, // 0x50c-0x510
pub pselcts: ReadWrite<u32, Psel::Register>, // 0x510-0x514
pub pselrxd: ReadWrite<u32, Psel::Register>, // 0x514-0x518
_reserved14: [u32; 3], ... | pub errorsrc: ReadWrite<u32, ErrorSrc::Register>, // 0x480-0x484
_reserved12: [u32; 31], // 0x484-0x500
pub enable: ReadWrite<u32, Uart::Register>, // 0x500-0x504
_reserved13: [u32; 1], // 0x504-0x508 | random_line_split |
uart.rs | 38-0x53c
pub rxd_amount: ReadOnly<u32, Counter::Register>, // 0x53c-0x540
_reserved16: [u32; 1], // 0x540-0x544
pub txd_ptr: ReadWrite<u32, Pointer::Register>, // 0x544-0x548
pub txd_maxcnt: ReadWrite<u32, Counter::Register>, // 0x548-0x54c
pub txd_amount: ReadOnly<u32, ... | {
regs.event_endtx.write(Event::READY::CLEAR);
let tx_bytes = regs.txd_amount.get() as usize;
let rem = self.remaining_bytes.get();
// More bytes transmitted than requested `return silently`
// Cause probably a hardware fault
// FIXME: Progate err... | conditional_block | |
plonk_util.rs | (x)` for a given `x`, where `n` is the injective function related to the Halo
/// endomorphism.
pub fn halo_n<C: HaloCurve>(s_bits: &[bool]) -> C::ScalarField {
// This is based on Algorithm 2 of the Halo paper, except that we start with (a, b) = (0, 0).
debug_assert_eq!(s_bits.len() % 2, 0, "Number of scalar ... | <F: Field>(coeffs: &[F], x: F) -> F {
let mut ans = F::ZERO;
let mut x_pow = F::ONE;
for &c in coeffs {
ans = ans + (c * x_pow);
x_pow = x_pow * x;
}
ans
}
/// Compute `[x^0, x^1, ..., x^(n - 1)]`.
pub fn powers<F: Field>(x: F, n: usize) -> Vec<F> {
let mut powers = Vec::new();
... | eval_poly | identifier_name |
plonk_util.rs | ProjectivePoint<C> {
msm_execute_parallel(pedersen_g_msm_precomputation, xs)
}
#[allow(dead_code)]
fn pedersen_commit<C: Curve>(
xs: &[C::ScalarField],
opening: C::ScalarField,
h: AffinePoint<C>,
pedersen_g_msm_precomputation: &MsmPrecomputation<C>,
) -> ProjectivePoint<C> {
// TODO: Couldn't ... | {
type F = <Tweedledee as Curve>::ScalarField;
let us = (0..10).map(|_| F::rand()).collect::<Vec<_>>();
let x = F::rand();
assert_eq!(
F::inner_product(&halo_s(&us), &powers(x, 1 << 10)),
halo_g(x, &us)
);
} | identifier_body | |
plonk_util.rs | n(x)` for a given `x`, where `n` is the injective function related to the Halo
/// endomorphism.
pub fn halo_n<C: HaloCurve>(s_bits: &[bool]) -> C::ScalarField {
// This is based on Algorithm 2 of the Halo paper, except that we start with (a, b) = (0, 0).
debug_assert_eq!(s_bits.len() % 2, 0, "Number of scalar... | if bit_lo {
endo_p_p
} else {
endo_p_n
}
} else if bit_lo {
p_p
} else {
p_n
};
acc = acc.double() + s;
}
acc.to_affine()
}
pub fn eval_poly<F: Field>(coeffs: &[F], x: F) -> F {
let ... | let s = if bit_hi { | random_line_split |
plonk_util.rs | (x)` for a given `x`, where `n` is the injective function related to the Halo
/// endomorphism.
pub fn halo_n<C: HaloCurve>(s_bits: &[bool]) -> C::ScalarField {
// This is based on Algorithm 2 of the Halo paper, except that we start with (a, b) = (0, 0).
debug_assert_eq!(s_bits.len() % 2, 0, "Number of scalar ... | ;
let (c, d) = if bit_hi { (sign, zero) } else { (zero, sign) };
a = a.double() + c;
b = b.double() + d;
}
a * C::ZETA_SCALAR + b
}
/// Compute `[n(s)].P` for a given `s`, where `n` is the injective function related to the Halo
/// endomorphism.
pub fn halo_n_mul<C: HaloCurve>(s_bits:... | {
C::ScalarField::NEG_ONE
} | conditional_block |
Zhihu__Crawler_JsonVersion.py | File)
self.opener = request.build_opener(request.HTTPCookieProcessor(self.cj), RedirectHandler())
self.client_info = 'monsterzpc@gmail.com'
self.passwd = 'Zpc920515'
self.url = 'https://www.zhihu.com/login/email'
self.target_page = ''
self.position = 0
print('''
#######################################... | s()
def profile_collector(self, text_path=None) :
'''
main entry for collecting user's profile including id, gender, education, career
'''
count = 0
self.cj.load()
user_list = []
# check the source of the data
if (text_path != None) :
with open(text_path, 'r') as source_list :
for line in sour... | ities').url | identifier_name |
Zhihu__Crawler_JsonVersion.py | File)
self.opener = request.build_opener(request.HTTPCookieProcessor(self.cj), RedirectHandler())
self.client_info = 'monsterzpc@gmail.com'
self.passwd = 'Zpc920515'
self.url = 'https://www.zhihu.com/login/email'
self.target_page = ''
self.position = 0
print('''
#######################################... |
def user_getter(sefl):
return User_Getter('https://www.zhihu.com/people/xiao-guai-shou-2/activities').urls()
def profile_collector(self, text_path=None) :
'''
main entry for collecting user's profile including id, gender, education, career
'''
count = 0
self.cj.load()
user_list = []... | conditional_block | |
Zhihu__Crawler_JsonVersion.py | File)
self.opener = request.build_opener(request.HTTPCookieProcessor(self.cj), RedirectHandler())
self.client_info = 'monsterzpc@gmail.com'
self.passwd = 'Zpc920515'
self.url = 'https://www.zhihu.com/login/email'
self.target_page = ''
self.position = 0
print('''
#######################################... | f):
'''
Execution of login
'''
if (self.client_info == '' or self.passwd == '') :
self.client_info = input('请输入账号:')
self.passwd = getpass('请输入密码:')
self.get_captcha_url()
captcha = input('请输入验证码:')
if (self.client_info.find("@") != -1) :
print('''正在使用邮箱登录...\n用户名:''' + self.client_info+ '\... | www.zhihu.com' + '/captcha.gif?r=' + str(int(time.time())) + '&type=login'
f = request.urlopen(url)
with open('./cap.png', 'wb') as image:
image.write(f.read())
image.close()
def login(sel | identifier_body |
Zhihu__Crawler_JsonVersion.py | #
#
# Created on : 03/07/17
# Last Modified :
#
# Author : Pengcheng Zhou(Kevin)
#
####################################################
import re
from urllib import parse, request, error
from multiprocessing import Pool
import http.cookiejar as Cookie
import time
import json
from getpass import getpass
import ssl
... | #!/usr/bin/python
# --*-- encoding:utf-8 --*--
####################################################
# Zhihu Auto-Aogin | random_line_split | |
main.rs | Cell<Option<TypeEncoder>>> = Mutex::new(RefCell::new(None));
type TypeMotor = Motor;
static G_MOTOR: Mutex<RefCell<Option<TypeMotor>>> = Mutex::new(RefCell::new(None));
static G_TIM: Mutex<RefCell<Option<Timer<TIM2>>>> = Mutex::new(RefCell::new(None));
static mut CURRENT_A: f32 = 0.0;
static mut CURRENT_B: f32 = 0.0... |
});
static mut SPI3: Option<TypeSpi3> = None;
static mut MOTOR: Option<TypeMotor> = None;
unsafe{
let mut spi3 = SPI3.get_or_insert_with(|| {
cortex_m::interrupt::free(|cs| {
G_SPI3.borrow(cs).replace(None).unwrap()
})
});
let device = p... | {
let _ = tim.wait();
} | conditional_block |
main.rs | Cell<Option<TypeEncoder>>> = Mutex::new(RefCell::new(None));
type TypeMotor = Motor;
static G_MOTOR: Mutex<RefCell<Option<TypeMotor>>> = Mutex::new(RefCell::new(None));
static G_TIM: Mutex<RefCell<Option<Timer<TIM2>>>> = Mutex::new(RefCell::new(None));
static mut CURRENT_A: f32 = 0.0;
static mut CURRENT_B: f32 = 0.0... |
/*
// LED Debug
cortex_m::interrupt::free(|cs| {
if let Some(ref mut led) = G_LED.borrow(cs).borrow_mut().as_mut() {
led.toggle().unwrap();
}
});
*/
}
#[interrupt]
fn TIM2() {
cortex_m::interrupt::free(|cs| {
if let Some(ref mut tim) = G_TIM.borrow(cs).borr... | {
// current sensing
unsafe {
let max_sample:u32 = (1 << 12) - 1;
let device = pac::Peripherals::steal();
device.ADC1.sr.modify(|_, w| w.jeoc().clear_bit());
let jdr1_data = device.ADC1.jdr1.read().jdata().bits();
let jdr1_offset = 48u32;
let so1 = ( ( (u32::fro... | identifier_body |
main.rs | Cell<Option<TypeEncoder>>> = Mutex::new(RefCell::new(None));
type TypeMotor = Motor;
static G_MOTOR: Mutex<RefCell<Option<TypeMotor>>> = Mutex::new(RefCell::new(None));
static G_TIM: Mutex<RefCell<Option<Timer<TIM2>>>> = Mutex::new(RefCell::new(None));
static mut CURRENT_A: f32 = 0.0;
static mut CURRENT_B: f32 = 0.0... | () {
// current sensing
unsafe {
let max_sample:u32 = (1 << 12) - 1;
let device = pac::Peripherals::steal();
device.ADC1.sr.modify(|_, w| w.jeoc().clear_bit());
let jdr1_data = device.ADC1.jdr1.read().jdata().bits();
let jdr1_offset = 48u32;
let so1 = ( ( (u32::... | ADC | identifier_name |
main.rs | static G_MOTOR: Mutex<RefCell<Option<TypeMotor>>> = Mutex::new(RefCell::new(None));
static G_TIM: Mutex<RefCell<Option<Timer<TIM2>>>> = Mutex::new(RefCell::new(None));
static mut CURRENT_A: f32 = 0.0;
static mut CURRENT_B: f32 = 0.0;
static mut CURRENT_C: f32 = 0.0;
static mut MOT_ANGLE: u16 = 0;
static mut MOT_ANGL... | type TypeEncoder<'a> = AS5048A<'a, TypeSpi3, gpioa::PA3<Output<PushPull>>>;
//static G_AS5048A: Mutex<RefCell<Option<TypeEncoder>>> = Mutex::new(RefCell::new(None));
type TypeMotor = Motor; | random_line_split | |
MouvementBrownien.py | = -math.floor(GRID_HEIGHT/2); # Coordonnees dans referentiel enonce
GRID_Y_MAX = math.floor(GRID_HEIGHT/2); # Coordonnees dans referentiel enonce
#
CANVAS_WIDTH = GRID_WIDTH*GRID_STEP; # Taille resultante du canvas (zone dessin)
CANVAS_HEIGHT = GRID_HEIGHT*GRID_STEP; # Taille resultante du canvas... |
# Lance la simulation with loop
## Problem1: we do no give a chance to the GUI elements to update => we need to force them
## Problem2: since the event loop is broken, the "Sortir" button does not work.
# def startSimulationLoop(canvas, label):
# particles = initParticles(NB_PARTICLES);
# for step in xrange(N | abel.configure(text="t="+str(t));
label.update_idletasks(); # THIS IS A DIRTY HACK!!!
| identifier_body |
MouvementBrownien.py | = -math.floor(GRID_HEIGHT/2); # Coordonnees dans referentiel enonce
GRID_Y_MAX = math.floor(GRID_HEIGHT/2); # Coordonnees dans referentiel enonce
#
CANVAS_WIDTH = GRID_WIDTH*GRID_STEP; # Taille resultante du canvas (zone dessin)
CANVAS_HEIGHT = GRID_HEIGHT*GRID_STEP; # Taille resultante du canvas... | # ty = currentParticle['y']-GRID_Y_MIN;
# txg = tx*GRID_STEP;
# tyg = ty*GRID_STEP;
# o = canvas.create_oval(txg-PARTICLE_SIZE, tyg-PARTICLE_SIZE,
# txg+PARTICLE_SIZE, tyg+PARTICLE_SIZE,
# outline=PARTICLE_COLOR, fill=PARTICLE... | random_line_split | |
MouvementBrownien.py | = -math.floor(GRID_HEIGHT/2); # Coordonnees dans referentiel enonce
GRID_Y_MAX = math.floor(GRID_HEIGHT/2); # Coordonnees dans referentiel enonce
#
CANVAS_WIDTH = GRID_WIDTH*GRID_STEP; # Taille resultante du canvas (zone dessin)
CANVAS_HEIGHT = GRID_HEIGHT*GRID_STEP; # Taille resultante du canvas... |
# Creation & Placement des elements graphiques
def initGUI(rootWindow):
##global canvas; ## for debugging purpose
canvas = tkinter.Canvas(rootWindow, width=CANVAS_WIDTH, height=CANVAS_HEIGHT);
canvas.config(background=CANVAS_BG_COLOR);
canvas.pack();
slider = tkinter.Scale(rootWindow, from_=0, to... | pauseButton.config(text="Pause"); | conditional_block |
MouvementBrownien.py | = -math.floor(GRID_HEIGHT/2); # Coordonnees dans referentiel enonce
GRID_Y_MAX = math.floor(GRID_HEIGHT/2); # Coordonnees dans referentiel enonce
#
CANVAS_WIDTH = GRID_WIDTH*GRID_STEP; # Taille resultante du canvas (zone dessin)
CANVAS_HEIGHT = GRID_HEIGHT*GRID_STEP; # Taille resultante du canvas... | canvas):
for x in xrange(0, CANVAS_WIDTH, GRID_STEP):
l1 = canvas.create_line(x, 0, x, CANVAS_HEIGHT, fill=GRID_COLOR);
canvas.itemconfig(l1, tags=("vl")); ## Useless
for y in xrange(0, CANVAS_HEIGHT, GRID_STEP):
l2 = canvas.create_line(0, y, CANVAS_WIDTH, y, fill=GRID_COLOR);
canvas.ite... | rawGrid( | identifier_name |
roster.go | (m *gtk.TreeStore, iter *gtk.TreeIter, index int) string {
val, _ := m.GetValue(iter, index)
v, _ := val.GetString()
return v
}
func (r *roster) getAccountAndJidFromEvent(bt *gdk.EventButton) (jid string, account *account, rowType string, ok bool) {
x := bt.X()
y := bt.Y()
path := new(gtk.TreePath)
found := r.v... | getFromModelIter | identifier_name | |
roster.go | builder.GetObject("accountMenu")
mn := obj.(*gtk.Menu)
builder.ConnectSignals(map[string]interface{}{
"on_connect": func() {
account.connect()
},
"on_disconnect": func() {
account.disconnect()
},
"on_dump_info": func() {
r.debugPrintRosterFor(account.session.GetConfig().Account)
},
})
connx,... | r.model.SetValue(parentIter, indexRowType, "account") | random_line_split | |
roster.go | int) string {
val, _ := m.GetValue(iter, index)
v, _ := val.GetString()
return v
}
func (r *roster) getAccountAndJidFromEvent(bt *gdk.EventButton) (jid string, account *account, rowType string, ok bool) {
x := bt.X()
y := bt.Y()
path := new(gtk.TreePath)
found := r.view.GetPathAtPos(int(x), int(y), path, nil, ... |
func (r *roster) onActivateBuddy(v *gtk.TreeView, path *gtk.TreePath) {
selection, _ := v.GetSelection()
defer selection.UnselectPath(path)
iter, err := r.model.GetIter(path)
if err != nil {
return
}
jid := getFromModelIter(r.model, iter, indexJid)
accountID := getFromModelIter(r.model, iter, indexAccountI... | {
bt := &gdk.EventButton{ev}
if bt.Button() == 0x03 {
jid, account, rowType, ok := r.getAccountAndJidFromEvent(bt)
if ok {
switch rowType {
case "peer":
r.createAccountPeerPopup(jid, account, bt)
case "account":
r.createAccountPopup(jid, account, bt)
}
}
}
return false
} | identifier_body |
roster.go | int) string {
val, _ := m.GetValue(iter, index)
v, _ := val.GetString()
return v
}
func (r *roster) getAccountAndJidFromEvent(bt *gdk.EventButton) (jid string, account *account, rowType string, ok bool) {
x := bt.X()
y := bt.Y()
path := new(gtk.TreePath)
found := r.view.GetPathAtPos(int(x), int(y), path, nil, ... |
if !p.Online {
return "offline"
}
switch p.Status {
case "dnd":
return "busy"
case "xa":
return "extended-away"
case "away":
return "away"
}
return "available"
}
func decideColorFor(p *rosters.Peer) string {
if !p.Online {
return "#aaaaaa"
}
return "#000000"
}
func createGroupDisplayName(pare... | {
return "unknown"
} | conditional_block |
models.py | . :)
def create_database(db_settings: Dict[str, Any], database_name: str) -> None:
with connect(**db_settings) as connection:
cursor = connection.cursor()
cursor.execute(f'CREATE DATABASE IF NOT EXISTS {database_name}')
def remove_database(db_settings: Dict[str, Any], database_name: str) -> None... | "Active"
]
}
Would result in the following create table query::
CREATE TABLE IF NOT EXISTS sports (ID INTEGER PRIMARY KEY AUTO_INCREMENT, Name VARCHAR(255), Slug VARCHAR(255), Active BOOLEAN)
"""
COLUMN_DEFINITIONS = 'definitions'
... | }
},
"required":[
"Name",
"Slug", | random_line_split |
models.py | . :)
def create_database(db_settings: Dict[str, Any], database_name: str) -> None:
with connect(**db_settings) as connection:
cursor = connection.cursor()
cursor.execute(f'CREATE DATABASE IF NOT EXISTS {database_name}')
def remove_database(db_settings: Dict[str, Any], database_name: str) -> None... |
def _fields_from_schema(self, schema: ISchema) -> List[str]:
return cast(List[str], schema.dict().keys()) # KeysView[str]
def _values_from_schema(self, schema: ISchema) -> List[Any]:
return cast(List[Any], schema.dict().values()) # KeysView[Any]
def select_fields(self, *field_names) ->... | schema_objects: List[ISchema] = []
for result in results:
row_data_mapped_to_fields = dict(zip(field_names, result))
schema_objects.append(self.schema.construct(**row_data_mapped_to_fields))
return schema_objects | identifier_body |
models.py | :)
def create_database(db_settings: Dict[str, Any], database_name: str) -> None:
with connect(**db_settings) as connection:
cursor = connection.cursor()
cursor.execute(f'CREATE DATABASE IF NOT EXISTS {database_name}')
def remove_database(db_settings: Dict[str, Any], database_name: str) -> None:... |
table_columns = ', '.join(field_queries)
with connect(**BaseModel.db_settings) as connection:
cursor = connection.cursor()
cursor.execute(
f'CREATE TABLE IF NOT EXISTS {self.table_name} (ID INTEGER PRIMARY KEY AUTO_INCREMENT, {table_columns})'
)
... | if KEY_REF in property:
property = ref_lookup(property, fields)
field_queries.append(
f'{property_name} {TYPE_LOOKUP[property[COLUMN_TYPE]]}'
) | conditional_block |
models.py | . :)
def create_database(db_settings: Dict[str, Any], database_name: str) -> None:
with connect(**db_settings) as connection:
cursor = connection.cursor()
cursor.execute(f'CREATE DATABASE IF NOT EXISTS {database_name}')
def remove_database(db_settings: Dict[str, Any], database_name: str) -> None... | (self, schema: ISchema) -> List[Any]:
return cast(List[Any], schema.dict().values()) # KeysView[Any]
def select_fields(self, *field_names) -> List[ISchema]:
field_names = self._clean_selected_fields(field_names)
fields_formatted = ', '.join(field_names)
query = f'{Keywords.Select.... | _values_from_schema | identifier_name |
wgl.rs | wgl")
.encode_wide()
.chain(Some(0).into_iter())
.collect::<Vec<_>>();
class.cbSize = mem::size_of::<WNDCLASSEXW>() as UINT;
class.lpszClassName = class_name.as_ptr();
class.lpfnWndProc = Some(DefWindowProcW);
RegisterCla... | extent: config.extent,
fbos: iter::once(fbo).collect(),
});
Ok(())
}
unsafe fn unconfigure_swapchain(&mut self, device: &Device) {
let gl = &device.share.context;
if let Some(old) = self.swapchain.take() {
for fbo in old.fbos {
... | );
self.swapchain = Some(Swapchain {
context, | random_line_split |
wgl.rs | wgl")
.encode_wide()
.chain(Some(0).into_iter())
.collect::<Vec<_>>();
class.cbSize = mem::size_of::<WNDCLASSEXW>() as UINT;
class.lpszClassName = class_name.as_ptr();
class.lpfnWndProc = Some(DefWindowProcW);
RegisterCla... | else {
GetProcAddress(lib, sym.as_ptr()) as *const _
}
});
Entry {
hwnd,
hdc: hdc as _,
wgl,
lib,
}
}
}
}
impl Drop for Entry {
fn drop(&mut self) {
unsafe {... | {
addr as *const _
} | conditional_block |
wgl.rs | gl")
.encode_wide()
.chain(Some(0).into_iter())
.collect::<Vec<_>>();
class.cbSize = mem::size_of::<WNDCLASSEXW>() as UINT;
class.lpszClassName = class_name.as_ptr();
class.lpfnWndProc = Some(DefWindowProcW);
RegisterClass... |
}
impl window::PresentationSurface<Backend> for Surface {
type SwapchainImage = native::ImageView;
unsafe fn configure_swapchain(
&mut self,
device: &Device,
config: window::SwapchainConfig,
) -> Result<(), window::CreationError> {
let gl = &device.share.context;
... | {
true
} | identifier_body |
wgl.rs | FD_TYPE_RGBA,
cColorBits: 8,
cRedBits: 0,
cRedShift: 0,
cGreenBits: 0,
cGreenShift: 0,
cBlueBits: 0,
cBlueShift: 0,
cAlphaBits: 8,
cAlphaShift: 0,
cAccumBits: 0... | make_current | identifier_name | |
RunExperiment.py | parser = argparse.ArgumentParser(description='Run simple linear track experiment.')
parser.add_argument('-P', '--serial-port', default='/dev/ttyACM0',
help='TTY device for USB-serial interface (e.g., /dev/ttyUSB0 or COM10)')
parser.add_argument('-C','--param-file', default='defaults.yaml',
... | else:
for cameraname, camera in Config['Cameras'].items():
if camera['RecordVideo']:
print('Over-riding camera configuration to not record video or timestamps!!!')
camera['RecordVideo'] = False
for cameraname, camera in Config['Cameras'].i... | if 'Cameras' in Config:
from treadmillio.uvccam.uvccam import RunCameraInterface
if DoLogCommands:
for cameraname, camera in Config['Cameras'].items():
camera['LogDirectory'] = log_directory | random_line_split |
RunExperiment.py | os.path.join(os.getcwd(), log_directory)
orig_log_directory = log_directory
k=1
while os.path.exists(log_directory):
k = k + 1
log_directory = orig_log_directory + '_' + str(k)
if log_directory != orig_log_directory:
warnings.warn('Specified experiment logs directory {} exists... | if DoLogCommands:
StateMachine.update_statemachine(state_log_writer.writerow) # update the state machine
else:
StateMachine.update_statemachine(None) # update the state machine | conditional_block | |
single_iceberg_model.py | Download timing start
start_download = time.time ()
print ("Downloading Web data to files")
#Downloading data and writing to files function
def download (url):
"""
Downloads web data and writes it to a file
Parameters
----------
url : String
Web address used as the data source.
Return... |
#print (ice)
#print (len (ice))
print ("Ice located and heights pulled")
"""
Stage 5: Calculating ice mass
"""
print ("Determining iceberg size")
#Pull heights
def calculations ():
pull_heights ()
ice_size = (len(ice))
#print ("ice size:", ice_size)
#Calculating ice volume above sea level
print ("... | radar_clean [i][j] = lidar_clean [i][j]
#print (radar_clean [i][j])
if (radar_clean [i][j]) > 100:
#print (radar_clean [i][j])
ice.append (lidar_clean [i][j]) | conditional_block |
single_iceberg_model.py | Download timing start
start_download = time.time ()
print ("Downloading Web data to files")
#Downloading data and writing to files function
def download (url):
"""
Downloads web data and writes it to a file
Parameters
----------
url : String
Web address used as the data source.
Return... | for i in range (len (radar_clean)):
for j in range (len (radar_clean)):
radar_clean [i][j] = lidar_clean [i][j]
#print (radar_clean [i][j])
if (radar_clean [i][j]) > 100:
#print (radar_clean [i][j])
ice.append (lidar_clean [i][j])
#print (i... |
"""
global ice
ice = [] | random_line_split |
single_iceberg_model.py | Download timing start
start_download = time.time ()
print ("Downloading Web data to files")
#Downloading data and writing to files function
def download (url):
|
#List of url web data
urls = [('Lidar', 'https://www.geog.leeds.ac.uk/courses/computing/study/core-python-odl2/assessment2/white1.lidar'),
('Radar', 'https://www.geog.leeds.ac.uk/courses/computing/study/core-python-odl2/assessment2/white1.radar')]
#Call download function
for x in urls:
download (x)
"""
St... | """
Downloads web data and writes it to a file
Parameters
----------
url : String
Web address used as the data source.
Returns
-------
None.
"""
path, url = url
r = requests.get (url, stream = True)
content = r.text
#print (content)
with open (path + '.txt'... | identifier_body |
single_iceberg_model.py | Download timing start
start_download = time.time ()
print ("Downloading Web data to files")
#Downloading data and writing to files function
def download (url):
"""
Downloads web data and writes it to a file
Parameters
----------
url : String
Web address used as the data source.
Return... | ():
"""
Generates two figures simultaneously displaying lidar and radar input
datasets.
Figures will appear in individual pop-up windows.
Returns
-------
None.
"""
plt.ylim = (0, 300)
plt.xlim = (0, 300)
#Set up lidar plot to figure 1
lidar_plot = plt.figure (1)
#... | show_graphs | identifier_name |
buffio_test.go | ()) // 4
br.UnreadByte() // 撤销吐出,即栈中弹出的a元素又放回来了
fmt.Println(br.Buffered()) // 5
tmp, _ = br.ReadByte()
fmt.Printf("%q\n", tmp) // 'a'
}
func TestReadRune1(t *testing.T) {
// ReadRune读取一个utf-8编码的unicode码值
chinese := "中国人"
s := strings.NewReader(chinese)
br := bufio.NewReader(s)
tmp, _, err := br.Rea... | b := bytes.N | identifier_name | |
buffio_test.go | s %v %v\n", b[:n], n, err) // 0 EOF
}
func TestBuffered1(t *testing.T) {
// 返回可以从缓存中读取的字节数
// func (b *Reader) Buffered() int { return b.w - b.r }
s := strings.NewReader("123456789")
br := bufio.NewReader(s)
b := make([]byte, 3)
br.Read(b)
fmt.Println(br.Buffered()) // 6
br.Read(b)
fmt.Println(br.Buffered())... | // 1、缓存不满,则将缓存填满后再次查找。
// 2、缓存是满的,则返回整个缓存,isPrefix 返回 true。
//
// 整个数据尾部“有一个换行标记”和“没有换行标记”的读取结果是一样。
//
// 如果 ReadLine 读取到换行标记,则调用 UnreadByte 撤销的是换行标记,
// 而不是返回的数据。
// func (b *Reader) ReadLine() (line []byte, isPrefix bool, err error)
s := strings.NewReader("123\nzzz")
br := bufio.NewReader(s)
for line, isP... | random_line_split | |
buffio_test.go | ([]byte, 3)
br.Read(b)
fmt.Println(br.Buffered()) // 6
br.Read(b)
fmt.Println(br.Buffered()) // 3
}
func TestReadByte1(t *testing.T) {
// ReadByte读取并返回一个字节。如果没有可用的数据,会返回错误。
// func (b *Reader) ReadByte() (c byte, err error)
origin := "abcd"
s := strings.NewReader(origin)
br := bufio.NewReader(s)
// 第一次读取
t... | r, 4096)
// func | conditional_block | |
buffio_test.go | err := []byte{0}, false, error(nil); len(line) > 0 && err == nil; {
line, isPrefix, err = br.ReadLine()
fmt.Printf("%q %t %v\n", line, isPrefix, err)
/*
"123" false <nil>
"zzz" false <nil>
"" false EOF
*/
}
}
func TestReadSlice1(t *testing.T) {
// ReadSlice 在 b 中查找 delim 并返回 delim 及其之前的所有数据。
// 该操... | r(s)
rw := bufio.NewReadWriter(br, bw)
word, err := rw.ReadString(' ')
if err != nil {
panic(err)
}
fmt.Printf("%s\n", word) // hello
_, err = rw.WriteString(",I'm coming")
if err != nil {
panic(err)
}
rw.Flush()
fmt.Println(b)
}
func TestNewScanner1(t *testing.T) {
// Scanner 提供了一个方便的接口来读取数据,例如遍历多行文本... | identifier_body | |
particle.rs | ];
}
#[rustfmt::skip]
const PARTICLE_TEXTURE_PIXELS: [u8; 64] = [
0, 0, 1, 1, 1, 1, 0, 0,
0, 1, 1, 1, 1, 1, 1, 0,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
0, 1, 1, 1, 1, 1, 1, 0,
0, 0, 1, 1, 1, 1, 0, 0,
];
pub struct ParticlePi... | else {
*pix *= i as u8;
}
}
let (diffuse_data, _) = palette.translate(&pixels);
create_texture(
device,
queue,
Some(&format!("particle texture {}", i)),
... | {
*pix = 0xFF;
} | conditional_block |
particle.rs | ];
}
#[rustfmt::skip]
const PARTICLE_TEXTURE_PIXELS: [u8; 64] = [
0, 0, 1, 1, 1, 1, 0, 0,
0, 1, 1, 1, 1, 1, 1, 0,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
0, 1, 1, 1, 1, 1, 1, 0,
0, 0, 1, 1, 1, 1, 0, 0,
];
pub struct ParticlePi... | (&self) -> &wgpu::RenderPipeline {
&self.pipeline
}
pub fn bind_group_layouts(&self) -> &[wgpu::BindGroupLayout] {
&self.bind_group_layouts
}
pub fn vertex_buffer(&self) -> &wgpu::Buffer {
&self.vertex_buffer
}
pub fn record_draw<'a, 'b, P>(
&'a self,
p... | pipeline | identifier_name |
particle.rs | ];
}
#[rustfmt::skip]
const PARTICLE_TEXTURE_PIXELS: [u8; 64] = [
0, 0, 1, 1, 1, 1, 0, 0,
0, 1, 1, 1, 1, 1, 1, 0,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
0, 1, 1, 1, 1, 1, 1, 0,
0, 0, 1, 1, 1, 1, 0, 0,
];
pub struct ParticlePi... | visibility: wgpu::ShaderStage::FRAGMENT,
ty: wgpu::BindingType::Sampler {
filtering: true,
comparison: false,
},
count: None,
},
// per-index texture array
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStage::FRAGMENT... | }
const BIND_GROUP_LAYOUT_ENTRIES: &[wgpu::BindGroupLayoutEntry] = &[
wgpu::BindGroupLayoutEntry {
binding: 0, | random_line_split |
particle.rs | ];
}
#[rustfmt::skip]
const PARTICLE_TEXTURE_PIXELS: [u8; 64] = [
0, 0, 1, 1, 1, 1, 0, 0,
0, 1, 1, 1, 1, 1, 1, 0,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
0, 1, 1, 1, 1, 1, 1, 0,
0, 0, 1, 1, 1, 1, 0, 0,
];
pub struct ParticlePi... | Self::set_push_constants(
pass,
Update(bump.alloc(VertexPushConstants {
transform: camera.view_projection() * translation * rotation,
})),
Retain,
Update(bump.alloc(FragmentPushConstants {
... | {
use PushConstantUpdate::*;
pass.set_pipeline(self.pipeline());
pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
pass.set_bind_group(0, &self.bind_group, &[]);
// face toward camera
let Angles { pitch, yaw, roll } = camera.angles();
let rotation = Angle... | identifier_body |
train_transformer.py | global_valid_step += 1
fout.write(' '.join(convert_ids_to_seq(output_seqs[0], vocab_bulider)) + '\n')
if (i+1) % opt.logstep == 0:
show_gen_seq(src, output_seqs, out_lens, tgt_gold, vocab_bulider, global_valid_step, mode='valid')
# summary
avg_loss = total_l... | model, opensub_dataloader, imsdb_dataloader,
opt.niter, criterion, optimizer, scheduler)
writer.close() | random_line_split | |
train_transformer.py | distinct_2_score += distinct_2(out_seqs, tgt_lens)
# summary writer
global_train_step += 1
writer.log_loss(loss.item()*ACCUMULATION, mode='train')
if (i+1) % ACCUMULATION == 0:
# clip_grad_norm_(model.parameters(), max_norm=5)
optimizer.step()
... | global global_train_step
model.train()
total_loss = 0.
bleu_score = 0.
distinct_1_score, distinct_2_score = 0., 0.
for i, (src, tgt, src_lens, tgt_lens) in tqdm(enumerate(dataloader, 0), desc='train', total=len(opensub_dataset)//opt.realbatch):
tgt_input = tgt[:, :-1]
tgt_gold... | identifier_body | |
train_transformer.py | =2)
# loss
loss = criterion(decoder_output_probs_T, tgt_gold) / ACCUMULATION
loss.backward()
total_loss += loss.item()
# calculate metrics
bleu_score += bleu_metirc(tgt_gold, out_seqs, tgt_lens)
distinct_1_score += distinct_1(out_seqs, tgt_lens)
di... | (model, train_loader, eval_loader, niter, criterion, optimizer, scheduler):
mylogger.log_info('Running Model')
for i in range(niter):
mylogger.log_info(f'EPOCH: {i}, lr: {optimizer.state_dict()["param_groups"][0]["lr"]}')
train(i, model, train_loader, criterion, optimizer, scheduler)
... | run_model | identifier_name |
train_transformer.py | =2)
# loss
loss = criterion(decoder_output_probs_T, tgt_gold) / ACCUMULATION
loss.backward()
total_loss += loss.item()
# calculate metrics
bleu_score += bleu_metirc(tgt_gold, out_seqs, tgt_lens)
distinct_1_score += distinct_1(out_seqs, tgt_lens)
di... |
def eval(epoch, model, dataloader, criterion, beam_size=2):
global global_valid_step
model.eval()
criterion.eval()
total_loss = 0.
bleu_score = 0.
distinct_1_score, distinct_2_score = 0., 0.
fout = open(os.path.join('./save/' + model_name + '/', model_name + '_' + str(epoch)), '... | avg_loss = (total_loss / opt.logstep) * ACCUMULATION
avg_bleu = bleu_score / opt.logstep
avg_distinct_1 = distinct_1_score / opt.logstep
avg_distinct_2 = distinct_2_score / opt.logstep
mylogger.log(
i, epoch, model, value=avg_loss, is_train=True,
... | conditional_block |
p21_sim.py | 693 #DUMMY
omega_MDM2 = 8.318 #DUMMY
omega_CD = 0.023 #DUMMY
omega_CDInk4 = 1 #DUMMY
omega_CE = 1 #DUMMY
omega_CA = 1 #DUMMY
omega_CACDC20 = 1 #DUMMY
omega_CB = 1 #DUMMY
omega_CBCDC20 = 1 #DUMMY
beta_E2FRb = 2 #DUMMY
beta_E2FRbMP = beta_E2FRb * 0.3 #DUMMY, but should be smaller than beta_E2FRb
beta_mdm2p14 = 1 #DUMMY
... | (t):
return 0 #dummy
def E7(t):
return 0 #dummy
#Fractions for inhibition/inactive complex formation.
#Each has a sanity check in case chief input is near zero.
sanity_threshold = 0.00001
def f(e2f, rb, rbmp):
if e2f < sanity_threshold:
return 0
return e2f**2 / (e2f + beta_E2FRb * rb + beta_E2... | E6 | identifier_name |
p21_sim.py | 693 #DUMMY
omega_MDM2 = 8.318 #DUMMY
omega_CD = 0.023 #DUMMY
omega_CDInk4 = 1 #DUMMY
omega_CE = 1 #DUMMY
omega_CA = 1 #DUMMY
omega_CACDC20 = 1 #DUMMY
omega_CB = 1 #DUMMY
omega_CBCDC20 = 1 #DUMMY
beta_E2FRb = 2 #DUMMY
beta_E2FRbMP = beta_E2FRb * 0.3 #DUMMY, but should be smaller than beta_E2FRb
beta_mdm2p14 = 1 #DUMMY
... |
def j(e7, e7prb, e7p21):
return e7 - e7prb - e7p21
#Variable key
#y[0] = p14
#y[1] = Ink4
#y[2] = p21
#y[3] = p53
#y[4] = Rb
#y[5] = pRb-P
#y[6] = pRb-PP
#y[7] = E2F
#y[8] = mdm2
#y[9] = pMDM2
#y[10] = CD (Cyclin D/CDK4-6 complex)
#y[11] = CE (Cyclin E/CDK2 complex)
#y[12] = CA (Cyclin A/CDK2 complex)
#y[13] = CB... | random_line_split | |
p21_sim.py | .693 #DUMMY
omega_MDM2 = 8.318 #DUMMY
omega_CD = 0.023 #DUMMY
omega_CDInk4 = 1 #DUMMY
omega_CE = 1 #DUMMY
omega_CA = 1 #DUMMY
omega_CACDC20 = 1 #DUMMY
omega_CB = 1 #DUMMY
omega_CBCDC20 = 1 #DUMMY
beta_E2FRb = 2 #DUMMY
beta_E2FRbMP = beta_E2FRb * 0.3 #DUMMY, but should be smaller than beta_E2FRb
beta_mdm2p14 = 1 #DUMMY... |
return e2f**2 / (e2f + beta_E2FRb * rb + beta_E2FRbMP * rbmp)
def g(mdm2, p14):
if mdm2 < sanity_threshold:
return 0
return mdm2**2 / (mdm2 + beta_mdm2p14 * p14)
def h(c, p21, cd, ce, ca, cb):
if c < sanity_threshold:
return 0
if ca+cb+cd+ce < sanity_threshold:
return 0
... | return 0 | conditional_block |
p21_sim.py | 693 #DUMMY
omega_MDM2 = 8.318 #DUMMY
omega_CD = 0.023 #DUMMY
omega_CDInk4 = 1 #DUMMY
omega_CE = 1 #DUMMY
omega_CA = 1 #DUMMY
omega_CACDC20 = 1 #DUMMY
omega_CB = 1 #DUMMY
omega_CBCDC20 = 1 #DUMMY
beta_E2FRb = 2 #DUMMY
beta_E2FRbMP = beta_E2FRb * 0.3 #DUMMY, but should be smaller than beta_E2FRb
beta_mdm2p14 = 1 #DUMMY
... |
def j(e7, e7prb, e7p21):
return e7 - e7prb - e7p21
#Variable key
#y[0] = p14
#y[1] = Ink4
#y[2] = p21
#y[3] = p53
#y[4] = Rb
#y[5] = pRb-P
#y[6] = pRb-PP
#y[7] = E2F
#y[8] = mdm2
#y[9] = pMDM2
#y[10] = CD (Cyclin D/CDK4-6 complex)
#y[11] = CE (Cyclin E/CDK2 complex)
#y[12] = CA (Cyclin A/CDK2 complex)
#y[13] = C... | if c < sanity_threshold:
return 0
if ca+cb+cd+ce < sanity_threshold:
return 0
return c**2 / (c + beta_cp21 * p21 * c / (ca+cb+cd+ce)) | identifier_body |
yaml.ts | instanceof type)) {
this._index = Number.MIN_SAFE_INTEGER;
}
}
return this as unknown as AncestryBuilder<X>;
}
/**
* Move up the path, asserting that the current node was a key of a mapping
* pair. The builder skips over the Pair to the parent YAMLMap.
*/
parentOfKey(): AncestryBu... | {
return false;
} | conditional_block | |
yaml.ts | this._index--;
}
}
if (type) {
if (!(this.get() instanceof type)) {
this._index = Number.MIN_SAFE_INTEGER;
}
}
return this as unknown as AncestryBuilder<X>;
}
/**
* Move up the path, asserting that the current node was a key of a mapping
* pair. The builder s... |
/**
* Get the path to the key of the Pair one level down the path to which the
* assertions have led.
*
* The path will be a subpath of the original path.
*/
// The `this` argument is for generics restriction of this method.
getKeyPath(this: AncestryBuilder<YAMLMap>): Node[] | null {
if (this... | {
if (this._index < 0) return null;
const path = this._path.slice(0, this._index + 1);
return path;
} | identifier_body |
yaml.ts | this._index--;
}
}
if (type) {
if (!(this.get() instanceof type)) {
this._index = Number.MIN_SAFE_INTEGER;
}
}
return this as unknown as AncestryBuilder<X>;
}
/**
* Move up the path, asserting that the current node was a key of a mapping
* pair. The builder s... |
/**
* Get the path to which the assertions have led.
*
* The path will be a subpath of the original path.
*/
getPath(): Node[] | null {
if (this._index < 0) return null;
const path = this._path.slice(0, this._index + 1);
return path;
}
/**
* Get the path to the key of the Pair one l... | return null;
} | random_line_split |
yaml.ts | this._index--;
}
}
if (type) {
if (!(this.get() instanceof type)) {
this._index = Number.MIN_SAFE_INTEGER;
}
}
return this as unknown as AncestryBuilder<X>;
}
/**
* Move up the path, asserting that the current node was a key of a mapping
* pair. The builder s... | (): N | null {
return (this._path[this._index] as N) || null;
}
/**
* Get the key of the Pair one level down the path.
*
* The key is returned only if it indeed is a string Scalar.
*/
// The `this` argument is for generics restriction of this method.
getStringKey(this: AncestryBuilder<YAMLMap>)... | get | identifier_name |
main.rs | first.starts_with("== "));
assert!(first.ends_with(" =="));
let name = first
.trim_end_matches(" ==")
.trim_start_matches("== ")
.to_owned();
let message = lines
.next()
.ok_or_else(|| anyhow!("No second line"))?
.trim()
... | .ok_or_else(|| anyhow!("No line after items"))?
.trim();
}
assert!(
next.is_empty(),
"Expected line after items to be empty, got '{}'",
next
);
next = lines
.next()
... | random_line_split | |
main.rs | _str(&mut self, output: &mut OutputVec, input: &str) -> anyhow::Result<String> {
log::debug!("Process 1: '{}'", input);
self.comp
.process_ascii(input, output)?
.expect(Stopped::Input)?;
log::debug!("Process 2: '\\n'");
self.comp
.process_ascii("\n", o... | {
let total = 1 << items.len();
for n in 0..total {
let mut explorer = initial_explorer.clone();
let cur_items: BTreeSet<String> = items
.iter()
.enumerate()
.filter_map(|(i, item)| {
if (n & (1 << i)) == 0 {
None
... | identifier_body | |
main.rs | line to be empty");
let next = lines
.next()
.ok_or_else(|| anyhow!("No fourth line"))?
.trim();
assert!(
next == "Doors here lead:",
"Expected third line to be 'Doors here lead:'"
);
let mut directions = Vec::new();
... | len | identifier_name | |
main.rs | .starts_with("== "));
assert!(first.ends_with(" =="));
let name = first
.trim_end_matches(" ==")
.trim_start_matches("== ")
.to_owned();
let message = lines
.next()
.ok_or_else(|| anyhow!("No second line"))?
.trim()
... |
}
}
// fn north(&mut self) -> anyhow::Result<String> {
// self.process_str("north")
// }
// fn south(&mut self) -> anyhow::Result<String> {
// self.process_str("south")
// }
// fn east(&mut self) -> anyhow::Result<String> {
// self.process_str("east")
// }... | {
let output = out.as_string()?;
log::warn!("process_str failure on input {}, output: {}", input, output);
Err(e)
} | conditional_block |
client.go | err := syscall.SetsockoptInt(s, syscall.SOL_SOCKET, syscall.SO_RCVBUF, bufferSize); err != nil {
return 0, nil, err
}
}
}
return s, lsa, nil
}
// Make syscall asking for all connections. Invoke 'cb' for each connection.
func queryAllConnections(bufferSize int, cb func(Conn), inetFamily uint8) error {
s, ... |
for _, attr := range attrs {
switch CtattrType(attr.Typ) {
case CtaTupleOrig:
parseTuple(attr.Msg, &conn.Orig)
case CtaTupleReply:
parseTuple(attr.Msg, &conn.Reply)
case CtaCountersOrig:
conn.Orig.Packets, conn.Orig.Bytes, _ = parseCounters(attr.Msg)
case CtaCountersReply:
conn.Reply.Packets, co... | {
return conn, err
} | conditional_block |
client.go | err := syscall.SetsockoptInt(s, syscall.SOL_SOCKET, syscall.SO_RCVBUF, bufferSize); err != nil {
return 0, nil, err
}
}
}
return s, lsa, nil
}
// Make syscall asking for all connections. Invoke 'cb' for each connection.
func queryAllConnections(bufferSize int, cb func(Conn), inetFamily uint8) error {
s, ... | () string{
return fmt.Sprintf("%d %s %v %v mark=%d\n",c.Orig.Proto,c.TCPState,c.Orig,c.Reply,c.CtMark)
}
// ConnTCP decides which way this connection is going and makes a ConnTCP.
func (c Conn) ConnTCP(local map[string]struct{}) *ConnTCP {
// conntrack gives us all connections, even things passing through, but it
//... | String | identifier_name |
client.go | err := syscall.SetsockoptInt(s, syscall.SOL_SOCKET, syscall.SO_RCVBUF, bufferSize); err != nil {
return 0, nil, err
}
}
}
return s, lsa, nil
}
// Make syscall asking for all connections. Invoke 'cb' for each connection.
func queryAllConnections(bufferSize int, cb func(Conn), inetFamily uint8) error {
s, ... | if msg.Header.Flags&(syscall.NLM_F_CREATE|syscall.NLM_F_EXCL) > 0 {
conn.MsgType = NfctMsgNew
}
case IpctnlMsgCtDelete:
conn.MsgType = NfctMsgDestroy
}
cb(*conn)
}
}
return nil
}
type Tuple struct {
Proto uint8
Src net.IP
SrcPort uint16
Dst net.IP
DstPort uint16
// Flow ... |
// Taken from conntrack/parse.c:__parse_message_type
switch CntlMsgTypes(nflnMsgType(msg.Header.Type)) {
case IpctnlMsgCtNew:
conn.MsgType = NfctMsgUpdate | random_line_split |
client.go | err := syscall.SetsockoptInt(s, syscall.SOL_SOCKET, syscall.SO_RCVBUF, bufferSize); err != nil {
return 0, nil, err
}
}
}
return s, lsa, nil
}
// Make syscall asking for all connections. Invoke 'cb' for each connection.
func queryAllConnections(bufferSize int, cb func(Conn), inetFamily uint8) error {
s, ... |
// ConnTCP decides which way this connection is going and makes a ConnTCP.
func (c Conn) ConnTCP(local map[string]struct{}) *ConnTCP {
// conntrack gives us all connections, even things passing through, but it
// doesn't tell us what the local IP is. So we use `local` as a guide
// what's local.
src := c.Orig.Src.... | {
return fmt.Sprintf("%d %s %v %v mark=%d\n",c.Orig.Proto,c.TCPState,c.Orig,c.Reply,c.CtMark)
} | identifier_body |
mongos.go | -operator",
"app.kubernetes.io/part-of": "percona-server-mongodb",
}
if cr.Spec.Sharding.Mongos.Labels != nil {
for k, v := range cr.Spec.Sharding.Mongos.Labels {
ls[k] = v
}
}
c, err := mongosContainer(cr, customConf.Type.IsUsable(), cfgInstances)
if err != nil {
return appsv1.DeploymentSpec{}, fm... | (cr *api.PerconaServerMongoDB, useConfigFile bool, cfgInstances []string) (corev1.Container, error) {
fvar := false
resources, err := CreateResources(cr.Spec.Sharding.Mongos.ResourcesSpec)
if err != nil {
return corev1.Container{}, fmt.Errorf("resource creation: %v", err)
}
volumes := []corev1.VolumeMount{
{... | mongosContainer | identifier_name |
mongos.go | ",
"app.kubernetes.io/part-of": "percona-server-mongodb",
}
if cr.Spec.Sharding.Mongos.Labels != nil {
for k, v := range cr.Spec.Sharding.Mongos.Labels {
ls[k] = v
}
}
c, err := mongosContainer(cr, customConf.Type.IsUsable(), cfgInstances)
if err != nil {
return appsv1.DeploymentSpec{}, fmt.Errorf(... |
return args
}
func volumes(cr *api.PerconaServerMongoDB, configSource VolumeSourceType) []corev1.Volume {
fvar, tvar := false, true
volumes := []corev1.Volume{
{
Name: InternalKey(cr),
VolumeSource: corev1.VolumeSource{
Secret: &corev1.SecretVolumeSource{
DefaultMode: &secretFileMode,
Secre... | {
args = append(args, fmt.Sprintf("--config=%s/mongos.conf", mongosConfigDir))
} | conditional_block |
mongos.go | ),
SchedulerName: cr.Spec.SchedulerName,
RuntimeClassName: cr.Spec.Sharding.Mongos.MultiAZ.RuntimeClassName,
},
},
Strategy: appsv1.DeploymentStrategy{
Type: appsv1.RollingUpdateDeploymentStrategyType,
RollingUpdate: &appsv1.RollingUpdateDeployment{
MaxSurge: &zero,
},
},
}, nil
}
f... | "app.kubernetes.io/name": "percona-server-mongodb", | random_line_split | |
mongos.go | .IsUsable(), cfgInstances)
if err != nil {
return appsv1.DeploymentSpec{}, fmt.Errorf("failed to create container %v", err)
}
initContainers := InitContainers(cr, operatorPod)
for i := range initContainers {
initContainers[i].Resources.Limits = c.Resources.Limits
initContainers[i].Resources.Requests = c.Reso... | {
fvar, tvar := false, true
volumes := []corev1.Volume{
{
Name: InternalKey(cr),
VolumeSource: corev1.VolumeSource{
Secret: &corev1.SecretVolumeSource{
DefaultMode: &secretFileMode,
SecretName: InternalKey(cr),
Optional: &fvar,
},
},
},
{
Name: "ssl",
VolumeSource: cor... | identifier_body | |
gridview.rs | ust_planned].commands_to_finalize.push(cmd)
}
pub fn rollback(&mut self, new_snapshot: &Snapshot) {
let old_planned: Vec<_> = self.planned.drain(..).collect();
self.planned
.push_back(new_snapshot.new_with_same_droplets());
assert_eq!(self.planned.len(), 1);
for pla... | ]; | random_line_split | |
gridview.rs | let mut ids = vec![]; // store corresponding ids to indeces
let mut matches = vec![]; // store similarity between blobs/droplets
let n = blobs.len();
// store the id of each droplet in its corresponding
// index in 'ids', then store the similarity of each
// droplet to each blo... |
pub fn snapshot_ensure(&mut self) {
if self.planned.is_empty() {
let last = self.completed.last().unwrap();
self.planned.push_back(last.new_with_same_droplets())
}
}
pub fn exec_snapshot(&self) -> &Snapshot {
self.completed.last().unwrap()
}
fn tic... | {
self.planned.back_mut().unwrap()
} | identifier_body |
gridview.rs | {
Disappeared,
DidNotMove,
Moved { from: Location, to: Location },
}
impl Snapshot {
pub fn new_with_same_droplets(&self) -> Snapshot {
let mut new_snapshot = Snapshot::default();
new_snapshot.droplets = self.droplets.clone();
// clear out the destination because we're doing t... | DropletDiff | identifier_name | |
wix.rs | data structure is needed because WIX requires each path to have its own `id` and `guid`.
#[derive(Serialize)]
struct | {
/// the GUID to use on the WIX XML.
guid: String,
/// the id to use on the WIX XML.
id: String,
/// the binary path.
path: String,
}
/// A Resource file to bundle with WIX.
/// This data structure is needed because WIX requires each path to have its own `id` and `guid`.
#[derive(Serialize, Clone)]
struc... | Binary | identifier_name |
wix.rs | data structure is needed because WIX requires each path to have its own `id` and `guid`.
#[derive(Serialize)]
struct Binary {
/// the GUID to use on the WIX XML.
guid: String,
/// the id to use on the WIX XML.
id: String,
/// the binary path.
path: String,
}
/// A Resource file to bundle with WIX.
/// Thi... | arch.to_string(),
wxs_file_name.to_string(),
format!(
"-dSourceDir={}",
settings.binary_path(main_binary).display()
),
];
let candle_exe = wix_toolset_path.join("candle.exe");
common::print_info(format!("running candle for {}", wxs_file_name).as_str())?;
let mut cmd = Command::new(... | {
let arch = match settings.binary_arch() {
"x86_64" => "x64",
"x86" => "x86",
target => {
return Err(crate::Error::ArchError(format!(
"unsupported target: {}",
target
)))
}
};
let main_binary = settings
.binaries()
.iter()
.find(|bin| bin.main())
.ok_o... | identifier_body |
wix.rs | _else(|| anyhow::anyhow!("Failed to get main binary"))?;
let args = vec![
"-arch".to_string(),
arch.to_string(),
wxs_file_name.to_string(),
format!(
"-dSourceDir={}",
settings.binary_path(main_binary).display()
),
];
let candle_exe = wix_toolset_path.join("candle.exe");
common:... | random_line_split | ||
collision.go | Collisions(cg *quad.CollisionGroup, now stime.Time) ([]entity.Entity, []entity.Entity) {
// Reset the resolved slice
phase.solved = phase.solved[:0]
// Generate a collision index for the collision group
phase.collisionIndex = cg.CollisionIndex()
// A map to store entities that still remain in the world
remainin... | }
var percentDamage float64
switch a.pathAction {
case nil:
if a.Cell() == assail.Cell() {
percentDamage = 1.0
}
default:
coordCollision := coord.NewCellCollision(*a.pathAction, assail.Cell())
percentDamage = coordCollision.OverlapAt(now)
}
damage := int(math.Floor(float64(assail.damage) * percentD... |
func (phase *narrowPhase) solveActorAssail(a *actor, assail assailEntity, collision quad.Collision, now stime.Time) []entity.Entity {
// Don't damage yourself
if assail.spawnedBy == a.actorEntity.Id() {
return []entity.Entity{a.Entity()} | random_line_split |
collision.go |
return false
}
func (phase narrowPhaseLocker) ResolveCollisions(cg *quad.CollisionGroup, now stime.Time) ([]entity.Entity, []entity.Entity) {
defer phase.ActorIndexLocker.RUnlock()
return newNarrowPhase(phase.ActorIndexLocker.RLock()).ResolveCollisions(cg, now)
}
// Implementation of the quad.NarrowPhaseHandler ... | {
if c.IsSameAs(solved) {
return true
}
} | conditional_block | |
collision.go | isions(cg *quad.CollisionGroup, now stime.Time) ([]entity.Entity, []entity.Entity) {
// Reset the resolved slice
phase.solved = phase.solved[:0]
// Generate a collision index for the collision group
phase.collisionIndex = cg.CollisionIndex()
// A map to store entities that still remain in the world
remaining :=... |
// Compare entity Id's with the entities in
// a collision and return the one that isn't
// the actor.
func otherEntityIn(a *actor, collision quad.Collision) entity.Entity {
var e entity.Entity
// figure out is prioritized actor is A or B in the collision
switch {
case a.actorEntity.Id() != collision.A.Id():
e... | {
switch {
case a.pathAction.Orig == b.pathAction.Dest:
return b
case b.pathAction.Orig == a.pathAction.Dest:
return a
default:
panic(fmt.Sprintf("unexpected graph state %v between %v & %v", collision, a, b))
}
} | identifier_body |
collision.go | Collisions(cg *quad.CollisionGroup, now stime.Time) ([]entity.Entity, []entity.Entity) {
// Reset the resolved slice
phase.solved = phase.solved[:0]
// Generate a collision index for the collision group
phase.collisionIndex = cg.CollisionIndex()
// A map to store entities that still remain in the world
remainin... | (a, b *actor) (*actor, *actor, coord.Collision) {
var collision coord.Collision
switch {
case a.pathAction == nil && b.pathAction != nil:
a, b = b, a
fallthrough
case a.pathAction != nil && b.pathAction == nil:
collision = coord.NewCellCollision(*a.pathAction, b.Cell())
// A or B may have had a previous c... | newActorActorCollision | identifier_name |
main.go | var trowner, trname string
var hbrev, brbd uint
var osvs []string
var logger = log.New(os.Stderr, "", log.LstdFlags)
func ferr(msg string, args ...interface{}) {
fmt.Printf(msg+"\n", args...)
os.Exit(1)
}
var ghc *github.Client
func init() {
pflag.StringVar(&rname, "release", "", "release name (ex: v1.0.0)")
pf... | var rname, npath, commitsha, ghtoken, taprepo, tapref, fpath, ftpath, targetoslist string
var draft, prerelease, dobuild bool | random_line_split | |
main.go | oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: ghtoken},
))
return github.NewClient(tc)
}
func checkLocalRepoVersion() {
cmd := exec.Command("git", "rev-parse", "HEAD")
out, err := cmd.Output()
if err != nil {
ferr("error getting git command output: %v", err)
}
if strings.TrimRight(string(out), "\n")... | {
logger.Printf("Creating Homebrew bottle...\n")
cwd, err := os.Getwd()
if err != nil {
return nil, nil, errors.Wrap(err, "error getting working directory")
}
rver := regexp.MustCompile("([0-9.]+)").FindString(rname)
basepath := filepath.Join(".", "psst", rver)
binpath := filepath.Join(basepath, "bin")
if err... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.