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
test1.go
egui.EndMenu() egui.Menu("Help") { egui.AddMenuItem("About", 0, nil, "hwg_MsgInfo(hb_version()+chr(10)+chr(13)+hwg_version(),\"About\")") } egui.EndMenu() } egui.EndMenu() pPanel := pWindow.AddWidget(&egui.Widget{Type: "paneltop", H: 40, AProps: map[string]string{"HStyle": "st1"}}) pPanel.AddWidge...
pDlg.AddWidget(&egui.Widget{Type: "updown", Name: "upd1", X: 280, Y: 68, W: 60, H: 24}) pDlg.AddWidget(&egui.Widget{Type: "group", X: 10, Y: 110, W: 180, H: 76, Title: "Check"}) pDlg.AddWidget(&egui.Widget{Type: "check", Name: "chk1", X: 24, Y: 124, W: 150, H: 24, Title: "Married"}) pDlg.AddWidget(&egui.Widget{Typ...
pDlg.AddWidget(&egui.Widget{Type: "combo", Name: "comb", X: 20, Y: 68, W: 160, H: 24, AProps: map[string]string{"AItems": egui.ToString("first", "second", "third")}}) pDlg.AddWidget(&egui.Widget{Type: "label", X: 220, Y: 68, W: 80, H: 24, Title: "Age:"})
random_line_split
test1.go
H: 32, Title: "Ok"}) egui.PLastWidget.SetCallBackProc("onclick", fsett4, "fsett4") pDlg.Activate() egui.EndPacket() return "" } func fsett4([]string) string { arr := egui.GetValues(egui.Wnd("dlg"), []string{"edi1", "edi2", "comb", "chk1", "chk2", "rg", "upd1"}) egui.PLastWindow.Close() egui.MsgInfo("Id: "+a...
{ egui.SelectColor(0, fsele_color, "fsele_color", "mm1") }
conditional_block
serial_play.py
.net/wiki/GD3_Specification # def readcstr(): chars = [] while True: c = self.__fd.read(2) # bytes(2) means two repetitions of value zero if c == bytes(2): return ("".join(chars)) chars.a...
def __init__(self, fd): self.__fd = fd self.__parse_header() self.__data = [] def dump_header(self): print("\x1b[2J") for k in ('id', 'str_version', 'total_samples', 'track_name', 'game_name', 'system_name','author_name', 'date'): ...
cnt = self.__header['gd3_offset'] - self.__header['vgm_data_offset'] self.__fd.seek(self.__header['vgm_data_offset']) self.__data = self.__fd.read(cnt)
identifier_body
serial_play.py
.net/wiki/GD3_Specification # def readcstr(): chars = [] while True: c = self.__fd.read(2) # bytes(2) means two repetitions of value zero if c == bytes(2): return ("".join(chars)) chars.a...
# 0x62: Wait 1/60th second elif data[i] == 0x62: wait_value = WAIT60TH - (time.time() - frame_t) time.sleep(wait_value if wait_value > 0 else 0) frame_t = time.time() i += 1 ...
wait_value = struct.unpack('< H', data[i+1:i+3])[0] samples_played += wait_value #print(wait_value) # Substract time spent in code wait_value = 1.0 * wait_value / 44100 - (time.time() - frame_t) ...
conditional_block
serial_play.py
/wiki/GD3_Specification # def readcstr(): chars = [] while True: c = self.__fd.read(2) # bytes(2) means two repetitions of value zero if c == bytes(2): return ("".join(chars)) chars.appen...
# 0x63: Wait 1/50th second elif data[i] == 0x63: wait_value = WAIT50TH - (time.time() - frame_t) time.sleep(wait_value if wait_value > 0 else 0) frame_t = time.time() i += 1 ...
time.sleep(wait_value if wait_value > 0 else 0) frame_t = time.time() i += 1 samples_played += 735
random_line_split
serial_play.py
/wiki/GD3_Specification # def readcstr(): chars = [] while True: c = self.__fd.read(2) # bytes(2) means two repetitions of value zero if c == bytes(2): return ("".join(chars)) chars.appen...
(data, header): samples_played = 0; song_min, song_sec = to_minsec(header['total_samples'], 44100) with serial.Serial(sys.argv[1], BAUD) as ser: print("\n\x1b[33;1mIninitalizing USB serial...\x1b[0m", end='') time.sleep(2) # Wait for Arduino reset frame_t = time.time()...
vgm_play
identifier_name
test_utils.py
memTrack tests outside a unittest""" def fail(self, msg=None): """Fail immediately, with the given message.""" raise Exception, msg def assert_(self, expr, msg=None): """Fail the test unless the expression is true.""" if not expr: raise Exception, msg ...
raise TestError('Requested wait() in child') if self_close: self.close_self() pid, exit_code = os.wait() self._exit_time = time.time() self._exit_code = exit_code def sync(self): """Wait for the other side of the fork to...
def wait(self, self_close=True): if self._inchild:
random_line_split
test_utils.py
memTrack tests outside a unittest""" def fail(self, msg=None): """Fail immediately, with the given message.""" raise Exception, msg def assert_(self, expr, msg=None): """Fail the test unless the expression is true.""" if not expr: raise Exception, msg ...
def _get_fork_time(self): return self._fork_time fork_time = property(fget=_get_fork_time) def _get_exit_time(self): if self._inchild: raise TestError('Exit time is available only in parent') return self._exit_time exit_time = propert...
if self._inchild: raise TestError('Requested wait() in child') pid, exit_code = os.wait() self._exit_time = time.time() self._exit_code = exit_code
identifier_body
test_utils.py
memTrack tests outside a unittest""" def fail(self, msg=None): """Fail immediately, with the given message.""" raise Exception, msg def assert_(self, expr, msg=None): """Fail the test unless the expression is true.""" if not expr: raise Exception, msg ...
action = re_result.group(1) pid = int(re_result.group(2)) address = re_result.group(3) if pid not in tracked_pids: continue f.write(line) f.write('\nProces...
continue
conditional_block
test_utils.py
memTrack tests outside a unittest""" def fail(self, msg=None): """Fail immediately, with the given message.""" raise Exception, msg def assert_(self, expr, msg=None): """Fail the test unless the expression is true.""" if not expr: raise Exception, msg ...
(self): return self._cpid cpid = property(fget=_get_cpid) def _get_ppid(self): return self._ppid ppid = property(fget=_get_ppid) def exit(self, status=0): if not self._inchild: raise TestError('Requested exit() in parent') os....
_get_cpid
identifier_name
network.rs
// Then, we add it to the crossroads and the roads. let road = Road::new(road_info); self.roads.push(road); self.crossroad_mut(src).roads[d1][side] = Some(id); self.crossroad_mut(dest).roads_arriving[d1][side] = Some(id); // Then, it builds the two corresponding edges in the gr...
{ '|' }
conditional_block
network.rs
{ pub x: usize, // Abscissa pub y: usize, // Ordinate } use std::ops::{ Index, IndexMut }; /// Allows indexing the grid by the crossroad coordinates. impl Index<CrossroadId> for Vec<Vec<Option<Crossroad>>> { type Output = Option<Crossroad>; #[inline] fn index(&self, index: CrossroadId) -> &O...
CrossroadId
identifier_name
network.rs
// with specified destination crossroad. STEP(i32), // The car performs a step of specified length. VANISH, // The car vanished. CROSS(RoadInfo), // The car crossed and is now on s...
pub enum Move { NONE, // None happened. SPAWN(RoadInfo, usize, CrossroadId), // The car has spawned at specified road, position,
random_line_split
network.rs
// They are indexed by direction and side. roads_arriving: Vec<Vec<Option<RoadId>>>, // Roads arriving at this crossroad. // They are indexed by direction and side. } impl Crossroad { /// Creates a new crossroad w...
self.crossroad_mut(src).roads[d1][side] = Some(id); self.crossroad_mut(dest).roads_arriving[d1][side] = Some(id); // Then, it builds the two corresponding edges in the graph. let (n1, n2) = { let c = self.crossroad(src); (c.nodes[d1], c.nodes[previous_direction(d...
{ // We get the parameters of the road. let (dx, dy, length) = src.join(dest); let length = length * self.cars_per_unit - self.cars_per_crossroad; let (d1, d2) = compute_directions(dx, dy, side); let id = self.roads.len(); // First, it builds the road in the network. ...
identifier_body
reflect_test.go
以 ` 开始和结尾的字符串。这个字符串在Go语言中被称为 Tag(标签)。一般用于给字段添加自定义信息,方便其他模块根据信息进行不同功能的处理。 Type int `json:"type" id:"100"` } ins := cat{Name: "mimi", Type: 1} // 获取结构体实例的反射类型对象 typeOfCat := reflect.TypeOf(ins) // 获得一个结构体类型共有多少个字段。如果类型不是结构体,将会触发panic。 for i := 0; i < typeOfCat.NumField(); i++ { // 获取每个成员的结构体字段类型,返回 StructField ...
random_line_split
reflect_test.go
// 2. 再通过reflect.Type的Field获取其Field for i := 0; i < getType.NumField(); i++ { field := getType.Field(i) // 取值 value := getValue.Field(i).Interface() fmt.Printf("%s: %v = %v\n", field.Name, field.Type, value) } // 获取方法 // 1. 先获取interface的reflect.Type,然后通过.NumMethod进行遍历 for i := 0; i < getType.NumMethod()...
identifier_name
reflect_test.go
4. // 反射对象的Kind方法描述的是基础类型,而不是静态类型。如果一个反射对象包含了用户定义类型的值,如下: type MyInt int var q MyInt = 7 // 虽然x的静态类型是MyInt而非int,但v的Kind依然是reflect.Int。Type可以区分开int和MyInt,但Kind无法做到。 ofV2 := reflect.ValueOf(q) fmt.Println("v2,type:", ofV2.Type()) fmt.Println("v2,kind:", ofV2.Kind()) } // 从反射对象到接口 //通过一个reflect.Value我们可以使用Interfa...
fmt.Println("type of pointer:", newValue.Type()) fmt.Println("settability of pointer:", newValue.CanSet()) // 重新赋值 newValue.SetFloat(77) fmt.Println("new value of pointer:", num) // 如果reflect.ValueOf的参数不是指针,会如何? pointer = reflect.ValueOf(num) fmt.Println("settability of pointer2:", pointer.CanSet()) //newVa...
q).Elem() typeOfT := s.Type() for i := 0; i < s.NumField(); i++ { f := s.Field(i) fmt.Printf("%d: %s %s = %v\n", i, typeOfT.Field(i).Name, f.Type(), f.Interface()) } s.Field(0).SetInt(77) s.Field(1).SetString("Sunset Strip") fmt.Println("t is now", t) } func TestReflectSetValue(t *testing.T) { var num f...
identifier_body
reflect_test.go
i++ { f := s.Field(i) fmt.Printf("%d: %s %s = %v\n", i, typeOfT.Field(i).Name, f.Type(), f.Interface()) } s.Field(0).SetInt(77) s.Field(1).SetString("Sunset Strip") fmt.Println("t is now", t) } func TestReflectSetValue(t *testing.T) { var num float64 = 1.2345 fmt.Println("old value of pointer:", num) ...
Println(a.Name(), a.Kind(), a.PkgPath()) field, b := a.FieldByNam
conditional_block
conn.go
() bool { _, isTLS := c.TLSConnectionState() return !c.server.AuthDisabled && (isTLS || c.server.AllowInsecureAuth) } // protocolError writes errors responses and closes the connection once too many // have occurred. func (c *Conn) protocolError(code int, ec EnhancedCode, msg string) { c.writeResponse(code, ec, msg...
authAllowed
identifier_name
conn.go
c.bdatPipe.CloseWithError(ErrDataReset) c.bdatPipe = nil } if c.session != nil { c.session.Logout() c.session = nil } return c.conn.Close() } // TLSConnectionState returns the connection's TLS connection state. // Zero values are returned if the connection doesn't use TLS. func (c *Conn) TLSConnectionSta...
if c.bdatPipe != nil {
random_line_split
conn.go
err return "" } return string(rune(char)) }) if replaceErr != nil { return "", replaceErr } return decoded, nil } func encodeXtext(raw string) string { var out strings.Builder out.Grow(len(raw)) for _, ch := range raw { if ch == '+' || ch == '=' { out.WriteRune('+') out.WriteString(strings....
{ args := strings.Fields(arg) if len(args) == 0 { c.writeResponse(501, EnhancedCode{5, 5, 4}, "Missing chunk size argument") return } if len(args) > 2 { c.writeResponse(501, EnhancedCode{5, 5, 4}, "Too many arguments") return } if !c.fromReceived || len(c.recipients) == 0 { c.writeResponse(502, Enhance...
identifier_body
conn.go
anced { c.writeResponse(250, EnhancedCode{2, 0, 0}, fmt.Sprintf("Hello %s", domain)) return } caps := []string{} caps = append(caps, c.server.caps...) if _, isTLS := c.TLSConnectionState(); c.server.TLSConfig != nil && !isTLS { caps = append(caps, "STARTTLS") } if c.authAllowed()
if c.server.EnableSMTPUTF8 { caps = append(caps, "SMTPUTF8") } if _, isTLS := c.TLSConnectionState(); isTLS && c.server.EnableREQUIRETLS { caps = append(caps, "REQUIRETLS") } if c.server.EnableBINARYMIME { caps = append(caps, "BINARYMIME") } if c.server.MaxMessageBytes > 0 { caps = append(caps, fmt.Spri...
{ authCap := "AUTH" for name := range c.server.auths { authCap += " " + name } caps = append(caps, authCap) }
conditional_block
lib.rs
(e), Err(Error(ErrorKind::WebDriver( WebDriverError {error: ErrorStatus::NoSuchElement, ..} ), _)) => sleep(Duration::from_millis(100)).await, Err(e) => break Err(e) } } } } } impl Driver { /...
( &self, locator: Locator, root: Option<WebElement>, ) -> Result<WebElement> { let cmd = match root { Option::None => WebDriverCommand::FindElement(locator.into()), Option::Some(elt) => { WebDriverCommand::FindElementElement(elt, locator.into()...
find
identifier_name
lib.rs
/// Wait for the specified element(s) to appear on the page pub async fn $name( &self, search: Locator, root: Option<WebElement> ) -> Result<$return_typ> { loop { match self.$search_fn(search.clone(), root.clone()).await { ...
($name:ident, $search_fn:ident, $return_typ:ty) => {
random_line_split
lib.rs
.0.issue_cmd(&cmd).await?; Ok(()) } /// Retrieve the currently active URL for this session. pub async fn current_url(&self) -> Result<url::Url> { match self.0.issue_cmd(&WebDriverCommand::GetCurrentUrl).await?.as_str() { Some(url) => Ok(url.parse()?), None => bail!(E...
{ match self.clone().attr(eid.clone(), String::from("href")).await? { None => bail!("no href attribute"), Some(href) => { let current = self.current_url().await?.join(&href)?; self.goto(current.as_str()).await } } }
identifier_body
lib.rs
MoveHeadLeft, /// Decrement the data pointer (to point to the next cell to the left) MoveHeadRight, /// If the byte at the data pointer is zero, then instead of moving the /// instruction pointer forward to the next command, jump it forward to the /// command after the matching ] command. Whi...
(s: &str) -> Vec<Self> { let mut instrs: Vec<BrainfuckInstr> = Vec::new(); for (l, pline) in s.lines().enumerate() { for (c, pbyte) in pline.bytes().enumerate() { if let Some(iraw) = BrainfuckInstrRaw::from_byte(pbyte) { instrs.push(BrainfuckInstr { ...
instrs_from_str
identifier_name
lib.rs
use thiserror::Error; /// Represents a Brainfuck Types Error. #[derive(Error, fmt::Debug)] pub enum BrainfuckTypesError { /// When an unmatched left or right bracket is found #[error("unmatched bracket, {0:?}")] UnmatchedBracket(BrainfuckInstr), } /// Represents the eight raw Brainfuck instructions. #[de...
use std::fmt; use std::io; use std::path::{Path, PathBuf};
random_line_split
sse_server.rs
= r#"/events"); evtSource.addEventListener("update", function(e) { localStorage.setItem('scrollPosition', window.scrollY); window.location.reload(true); }); window.addEventListener('load', function() { if(localStorage.getItem('scrollPosition') !== null) window.scrollTo(0...
{ /// Receiver side of the channel where `update` events are sent. rx: Receiver<SseToken>, /// Byte stream coming from a TCP connection. pub(crate) stream: TcpStream, /// A list of referenced relative URLs to images or other /// documents as they appear in the delivered Tp-Note documents. /...
ServerThread
identifier_name
sse_server.rs
= r#"/events"); evtSource.addEventListener("update", function(e) { localStorage.setItem('scrollPosition', window.scrollY); window.location.reload(true); }); window.addEventListener('load', function() { if(localStorage.getItem('scrollPosition') !== null) window.scrollTo(0...
'tcp_connection: loop { // This is inspired by the Spook crate. // Read the request. let mut read_buffer = [0u8; TCP_READ_BUFFER_SIZE]; let mut buffer = Vec::new(); let (method, path) = 'assemble_tcp_chunks: loop { // Read the request, ...
{ // One reference is hold by the `manage_connections` thread and does not count. // This is why we subtract 1. let open_connections = Arc::<()>::strong_count(&self.conn_counter) - 1; log::trace!( "TCP port local {} to peer {}: New incoming TCP connection ({} open).", ...
identifier_body
sse_server.rs
= r#"/events"); evtSource.addEventListener("update", function(e) { localStorage.setItem('scrollPosition', window.scrollY); window.location.reload(true); }); window.addEventListener('load', function() { if(localStorage.getItem('scrollPosition') !== null) window.scrollTo(0...
pub enum SseToken { /// Server-Sent-Event token to request nothing but check if the client is still /// there. Ping, /// Server-Sent-Event token to request a page update. Update, } pub fn manage_connections( event_tx_list: Arc<Mutex<Vec<SyncSender<SseToken>>>>, listener: TcpListener, do...
/// Server-Sent-Event tokens our HTTP client has registered to receive. #[derive(Debug, Clone, Copy)]
random_line_split
inner_product_proof.rs
Hprime_factors: I, mut G_vec: Vec<RistrettoPoint>, mut H_vec: Vec<RistrettoPoint>, mut a_vec: Vec<Scalar>, mut b_vec: Vec<Scalar>, ) -> InnerProductProof where I: IntoIterator, I::Item: Borrow<Scalar>, { // Create slices G, H, a, b backed by th...
} } /// Computes an inner product of two vectors /// \\[ /// {\langle {\mathbf{a}}, {\mathbf{b}} \rangle} = \sum\_{i=0}^{n-1} a\_i \cdot b\_i. /// \\] /// Panics if the lengths of \\(\mathbf{a}\\) and \\(\mathbf{b}\\) are not equal. pub fn inner_product(a: &[Scalar], b: &[Scalar]) -> Scalar { let mut out =...
{ Err(()) }
conditional_block
inner_product_proof.rs
Hprime_factors: I, mut G_vec: Vec<RistrettoPoint>, mut H_vec: Vec<RistrettoPoint>, mut a_vec: Vec<Scalar>, mut b_vec: Vec<Scalar>, ) -> InnerProductProof where I: IntoIterator, I::Item: Borrow<Scalar>, { // Create slices G, H, a, b backed by th...
( &self, transcript: &mut ProofTranscript, ) -> (Vec<Scalar>, Vec<Scalar>, Vec<Scalar>) { let lg_n = self.L_vec.len(); let n = 1 << lg_n; // 1. Recompute x_k,...,x_1 based on the proof transcript let mut challenges = Vec::with_capacity(lg_n); for (L, R) in s...
verification_scalars
identifier_name
inner_product_proof.rs
(), n); assert_eq!(a.len(), n); assert_eq!(b.len(), n); // XXX save these scalar mults by unrolling them into the // first iteration of the loop below for (H_i, h_i) in H.iter_mut().zip(Hprime_factors.into_iter()) { *H_i = (&*H_i) * h_i.borrow(); } l...
// P would be determined upstream, but we need a correct P to check the proof. // // To generate P = <a,G> + <b,H'> + <a,b> Q, compute // P = <a,G> + <b',H> + <a,b> Q,
random_line_split
spotutils.py
-73.06, 42.20, 13.46, -51.06, 12.15, -37.03, -82.06, 20.90, -28.28, -73.06, 42.20, 13.46, -51.06]) sca.scale = 133.08 # reference Zernikes ZernRef = EmptyClass() ZernRef.data = numpy.loadtxt('pupils/zernike_ref.txt')[:,-22:] * 1.38 # filter data FilterData = numpy.loadtxt('pupils/filter.dat') FilterData[:,1:] /= n...
c[i] = sed.Nlambda(x[i]) * filter.Tlambda(x[i]) o = numpy.ones((npts)) I = numpy.zeros((2*nOrder)) lctr = numpy.mean(x) for k in range(2*nOrder): I[k] = numpy.sum(o*(x-lctr)**k*c) # orthogonal polynomial p_n # require sum_{j=0}^n coef_{n-j} I_{j+k} = 0 or # sum_{j=0}^{n-1} coef_{n-j} I_{j+k} = ...
c = numpy.zeros((npts)) for i in range(npts):
random_line_split
spotutils.py
-73.06, 42.20, 13.46, -51.06, 12.15, -37.03, -82.06, 20.90, -28.28, -73.06, 42.20, 13.46, -51.06]) sca.scale = 133.08 # reference Zernikes ZernRef = EmptyClass() ZernRef.data = numpy.loadtxt('pupils/zernike_ref.txt')[:,-22:] * 1.38 # filter data FilterData = numpy.loadtxt('pupils/filter.dat') FilterData[:,1:] /= n...
# psi is a vector of Zernikes, in wavelengths # mask information: (currently none) # scale = sampling (points per lambda/D) # Nstep = # grid points # output normalized to sum to 1 def mono_psf(psi, mask, scale, Nstep): if hasattr(mask, 'N'): if hasattr(mask, 'spline'): interp_spline = mask.spline else...
for k in range(36): psi = numpy.zeros(36) psi[k] = 1 N=5 M = zernike_map_noll(psi, N, N/(N-1)) print(' *** Zernike {:2d} ***'.format(k+1)) for j in range(N): out = '' for i in range(N): out = out + ' {:10.5f}'.format(M[j,i]) print(out) print('')
identifier_body
spotutils.py
((2*nmax+1,Ngrid,Ngrid)) for i in range(1,nmax+1): rpows[i,:,:] = rho**i for i in range(0,nmax+1): trigphi[i,:,:] = numpy.cos(i*phi) for i in range(1,nmax+1): trigphi[-i,:,:] = numpy.sin(i*phi) # loop over Zernikes for n in range(nmax+1): for m in range(-n,n+1,2): Z = numpy.zeros((Ngrid,Ngrid)) ...
if addInfo.FastMode: c = dwl[i]
conditional_block
spotutils.py
(self, lambda_): # smoothed tophat if self.type=='STH': lmin = self.info[0]; dlmin = lmin*.02 lmax = self.info[1]; dlmax = lmax*.02 return((numpy.tanh((lambda_-lmin)/dlmin)-numpy.tanh((lambda_-lmax)/dlmax))/2.) # interpolated file # info shape (N,2) -- info[:,0] = wavelength, info[:,1...
Tlambda
identifier_name
pim_rpf_hash_bag.pb.go
Info_PimRpfHashBag_KEYS proto.InternalMessageInfo func (m *PimRpfHashBag_KEYS) GetVrfName() string { if m != nil { return m.VrfName } return "" } func (m *PimRpfHashBag_KEYS) GetSafName() string { if m != nil { return m.SafName } return "" } func (m *PimRpfHashBag_KEYS) GetTopologyName() string { if m != ...
return "" } func (m *PimRpfHashBag_KEYS) GetSourceAddress() string { if m != nil { return m.SourceAddress } return "" } func (m *PimRpfHashBag_KEYS) GetMofrr() uint32 { if m != nil { return m.Mofrr } return 0 } type PimAddrtype struct { AfName string `protobuf:"bytes,1,opt,name=af_name,j...
{ return m.TopologyName }
conditional_block
pim_rpf_hash_bag.pb.go
Info_PimRpfHashBag_KEYS proto.InternalMessageInfo func (m *PimRpfHashBag_KEYS) GetVrfName() string { if m != nil { return m.VrfName } return "" } func (m *PimRpfHashBag_KEYS) GetSafName() string { if m != nil { return m.SafName } return "" } func (m *PimRpfHashBag_KEYS) GetTopologyName() string { if m != ...
func (m *PimAddrtype) GetIpv6Address() string { if m != nil { return m.Ipv6Address } return "" } type PimRpfHashBag struct { NextHopMultipathEnabled bool `protobuf:"varint,50,opt,name=next_hop_multipath_enabled,json=nextHopMultipathEnabled,proto3" json:"next_hop_multipath_enabled,omitempty"` NextHop...
{ if m != nil { return m.Ipv4Address } return "" }
identifier_body
pim_rpf_hash_bag.pb.go
Info_PimRpfHashBag_KEYS proto.InternalMessageInfo func (m *PimRpfHashBag_KEYS) GetVrfName() string { if m != nil { return m.VrfName } return "" } func (m *PimRpfHashBag_KEYS) GetSafName() string { if m != nil { return m.SafName } return "" } func (m *PimRpfHashBag_KEYS) GetTopologyName() string { if m != ...
() { proto.RegisterType((*PimRpfHashBag_KEYS)(nil), "cisco_ios_xr_ipv4_pim_oper.pim.standby.vrfs.vrf.safs.saf.rpf_hash_sources.rpf_hash_source.pim_rpf_hash_bag_KEYS") proto.RegisterType((*PimAddrtype)(nil), "cisco_ios_xr_ipv4_pim_oper.pim.standby.vrfs.vrf.safs.saf.rpf_hash_sources.rpf_hash_source.pim_addrtype") prot...
init
identifier_name
pim_rpf_hash_bag.pb.go
Info_PimRpfHashBag_KEYS proto.InternalMessageInfo func (m *PimRpfHashBag_KEYS) GetVrfName() string { if m != nil { return m.VrfName } return "" } func (m *PimRpfHashBag_KEYS) GetSafName() string { if m != nil { return m.SafName } return "" } func (m *PimRpfHashBag_KEYS) GetTopologyName() string { if m != ...
type PimRpfHashBag struct { NextHopMultipathEnabled bool `protobuf:"varint,50,opt,name=next_hop_multipath_enabled,json=nextHopMultipathEnabled,proto3" json:"next_hop_multipath_enabled,omitempty"` NextHopAddress *PimAddrtype `protobuf:"bytes,51,opt,name=next_hop_address,json=nextHopAddress,proto3...
if m != nil { return m.Ipv6Address } return "" }
random_line_split
index.js
does not include neaName. * @property {int} FAILED_TO_INIT Configuration infomation is okay, but NAPI was unable to start successfully. * @property {int} ERROR An error occurred, likely an exception, possibly involving the parameters provided. * @property {int} IMPOSSIBLE ...
static get LogLevel () { return LogLevel; } /** * <p>Create bindings for the Nymi API</p> * * @constructor * @param {boolean} [nymulator=false] TRUE create bindings for networked library, FALSE create bindings for native library. */ constructor (nymulator) { ...
random_line_split
index.js
not include neaName. * @property {int} FAILED_TO_INIT Configuration infomation is okay, but NAPI was unable to start successfully. * @property {int} ERROR An error occurred, likely an exception, possibly involving the parameters provided. * @property {int} IMPOSSIBLE *...
{ return LogLevel; } /** * <p>Create bindings for the Nymi API</p> * * @constructor * @param {boolean} [nymulator=false] TRUE create bindings for networked library, FALSE create bindings for native library. */ constructor (nymulator) { nymulator = nymulator ...
el ()
identifier_name
index.js
not include neaName. * @property {int} FAILED_TO_INIT Configuration infomation is okay, but NAPI was unable to start successfully. * @property {int} ERROR An error occurred, likely an exception, possibly involving the parameters provided. * @property {int} IMPOSSIBLE *...
if (outcome === NapiBinding.GetOutcome.OKAY) { json = JSON.parse(buf.readCString(0)); } } catch (
outcome = _g(this, 'binding').napiGet(buf, len.deref(), len); }
conditional_block
index.js
not include neaName. * @property {int} FAILED_TO_INIT Configuration infomation is okay, but NAPI was unable to start successfully. * @property {int} ERROR An error occurred, likely an exception, possibly involving the parameters provided. * @property {int} IMPOSSIBLE *...
/** * LogLevel * * @static * @return {LogLevel} */ static get LogLevel () { return LogLevel; } /** * <p>Create bindings for the Nymi API</p> * * @constructor * @param {boolean} [nymulator=false] TRUE create bindings for networked library, FALSE cre...
return ConfigOutcome; }
identifier_body
run.py
hrr.Vocabulary(D) keys = [noise_vocab.parse(str(x)) for x in range(2*num+1)] def f(input_vec): input_vec = hrr.HRR(data=input_vec) partner_key = random.choice(keys) pair_keys = filter(lambda x: x != partner_key, keys) pairs = random.sample(pair_keys, 2 * num) p0 = (p...
errors.append(controller.latest_rmse) logging.info("RMSE for run: %g" % (controller.latest_rmse)) if len(errors) > 0: mean = np.mean def var(x): if len(x) > 1: return float(sum((np.array(x) - mean(x))**2)) / float(len(x) - 1) else: ...
run = 0 run_length = (options.learningpres + options.testingpres) * trial_length * options.dt logging.info("Run length: %g" % (run_length)) controller = network._get_node('EC') errors = [] while run < options.num_runs: logging.info("Starting run: %d" % (run + 1)) network.run(run_leng...
identifier_body
run.py
(): yield learning yield testing return f def simple_noise(noise): def f(input_vec): v = input_vec + noise * hrr.HRR(D).v v = v / np.sqrt(sum(v**2)) return v return f def hrr_noise(D, num): noise_vocab = hrr.Vocabulary(D) keys = [noise_vocab.parse(str(x))...
f
identifier_name
run.py
hrr.Vocabulary(D) keys = [noise_vocab.parse(str(x)) for x in range(2*num+1)] def f(input_vec): input_vec = hrr.HRR(data=input_vec) partner_key = random.choice(keys) pair_keys = filter(lambda x: x != partner_key, keys) pairs = random.sample(pair_keys, 2 * num) p0 = (p...
help="Dimension of the vectors that the cleanup operates on") parser.add_option("-V", "--numvectors", dest="num_vecs", default=4, type="int", help="Number of vectors that the cleanup will try to learn") parser.add_option("--dt", default=0.001, type="float", help="Time step") pars...
help="Number of neurons per dimension for other ensembles") parser.add_option("-D", "--dim", dest="D", default=16, type="int",
random_line_split
run.py
hrr.Vocabulary(D) keys = [noise_vocab.parse(str(x)) for x in range(2*num+1)] def f(input_vec): input_vec = hrr.HRR(data=input_vec) partner_key = random.choice(keys) pair_keys = filter(lambda x: x != partner_key, keys) pairs = random.sample(pair_keys, 2 * num) p0 = (p...
else: options.learning_noise = simple_noise(options.learning_noise) options.testing_noise = simple_noise(options.testing_noise) options.schedule_func = make_simple_test_schedule(options.learningpres, options.testingpres) options_dict = options.__dict__ network = lc.make_learnable_cle...
options.learning_noise = hrr_noise(options.D, options.learning_noise) options.testing_noise = hrr_noise(options.D, options.testing_noise)
conditional_block
tab_switch_cuj.go
Recorder. WPRArchiveName = "tab_switch_cuj.wprgo" ) // TabSwitchParam holds parameters of tab switch cuj test variations. type TabSwitchParam struct { BrowserType browser.Type // Chrome type. } // tabSwitchVariables holds all the necessary variables used by the test. type tabSwitchVariables struct { param TabSw...
vars.bTconn, err = vars.br.TestAPIConn(ctx) if err != nil { return nil, errors.Wrap(err, "failed to get browser TestAPIConn") } vars.recorder, err = cujrecorder.NewRecorder(ctx, vars.cr, vars.bTconn, nil, cujrecorder.RecorderOptions{}) if err != nil { return nil, errors.Wrap(err, "failed to create a recorde...
{ return nil, errors.Wrap(err, "failed to open the browser") }
conditional_block
tab_switch_cuj.go
ujRecorder. WPRArchiveName = "tab_switch_cuj.wprgo" ) // TabSwitchParam holds parameters of tab switch cuj test variations. type TabSwitchParam struct { BrowserType browser.Type // Chrome type. } // tabSwitchVariables holds all the necessary variables used by the test. type tabSwitchVariables struct { param Tab...
(ctx context.Context, tconn *chrome.TestConn, tabs *[]map[string]interface{}, tabIndexWithinWindow int, timeout time.Duration) error { // Define parameters for API calls activateTabProperties := map[string]interface{}{ "active": true, } // Find id of tab with positional index. tabID := int((*tabs)[tabIndexWithi...
focusTab
identifier_name
tab_switch_cuj.go
ujRecorder. WPRArchiveName = "tab_switch_cuj.wprgo" ) // TabSwitchParam holds parameters of tab switch cuj test variations. type TabSwitchParam struct { BrowserType browser.Type // Chrome type. } // tabSwitchVariables holds all the necessary variables used by the test. type tabSwitchVariables struct { param Tab...
topRow, err := input.KeyboardTopRowLayout(ctx, kw) if err != nil { return errors.Wrap(err, "failed to obtain the top-row layout") } if err = kw.Accel(ctx, topRow.VolumeMute); err != nil { return errors.Wrap(err, "failed to press mute key") } return nil } // findAnchorURLs returns the unique URLs of the anc...
return errors.Wrap(err, "failed to open the keyboard") } defer kw.Close()
random_line_split
tab_switch_cuj.go
Recorder. WPRArchiveName = "tab_switch_cuj.wprgo" ) // TabSwitchParam holds parameters of tab switch cuj test variations. type TabSwitchParam struct { BrowserType browser.Type // Chrome type. } // tabSwitchVariables holds all the necessary variables used by the test. type tabSwitchVariables struct { param TabSw...
func retrieveAllTabs(ctx context.Context, tconn *chrome.TestConn, timeout time.Duration) ([]map[string]interface{}, error) { emptyQuery := map[string]interface{}{} // Get all tabs var tabs []map[string]interface{} ctx, cancel := context.WithTimeout(ctx, timeout) defer cancel() err := tconn.Call(ctx, &tabs, `ta...
{ query := map[string]interface{}{ "status": "loading", "currentWindow": true, } return testing.Poll(ctx, func(ctx context.Context) error { var tabs []map[string]interface{} if err := tconn.Call(ctx, &tabs, `tast.promisify(chrome.tabs.query)`, query); err != nil { return testing.PollBreak(err) } ...
identifier_body
main.rs
Corrode/C.hs"; // let a = "./test/input.hs"; println!("file: {}", a); let mut file = File::open(a).unwrap(); let mut contents = String::new(); file.read_to_string(&mut contents).unwrap(); if a.ends_with(".lhs") { contents = strip_lhs(&contents); } let contents = parser_haskell::...
match parser_haskell::parse(&mut errors, &contents) { Ok(v) => { // errln!("{:?}", v); if dump_ast { println!("{}", format!("{:#?}", v).replace(" ", " ")); } else { writeln!(file_out, "// Original file: {:?}", p.file_name().unwrap())?;...
{ let mut contents = input.to_string(); let mut file_out = String::new(); let mut rust_out = String::new(); // Parse out HASKELL /HASKELL RUST /RUST sections. let re = Regex::new(r#"HASKELL[\s\S]*?/HASKELL"#).unwrap(); contents = re.replace(&contents, "").to_string(); let re = Regex::new(r#...
identifier_body
main.rs
.hs"; println!("file: {}", a); let mut file = File::open(a).unwrap(); let mut contents = String::new(); file.read_to_string(&mut contents).unwrap(); if a.ends_with(".lhs") { contents = strip_lhs(&contents); } let contents = parser_haskell::preprocess(&contents); // let mut a = ...
} if (arg_run || arg_out.is_some()) && arg_ast { bail!("Cannot use --ast and (--run or --out) at the same time.");
random_line_split
main.rs
Corrode/C.hs"; // let a = "./test/input.hs"; println!("file: {}", a); let mut file = File::open(a).unwrap(); let mut contents = String::new(); file.read_to_string(&mut contents).unwrap(); if a.ends_with(".lhs") { contents = strip_lhs(&contents); } let contents = parser_haskell::...
(input: &str, p: &Path, inline_mod: bool, dump_ast: bool) -> Result<(String, String)> { let mut contents = input.to_string(); let mut file_out = String::new(); let mut rust_out = String::new(); // Parse out HASKELL /HASKELL RUST /RUST sections. let re = Regex::new(r#"HASKELL[\s\S]*?/HASKELL"#).unwr...
convert_file
identifier_name
main.rs
Corrode/C.hs"; // let a = "./test/input.hs"; println!("file: {}", a); let mut file = File::open(a).unwrap(); let mut contents = String::new(); file.read_to_string(&mut contents).unwrap(); if a.ends_with(".lhs") { contents = strip_lhs(&contents); } let contents = parser_haskell::...
else { writeln!(file_out, "#[macro_use] use corollary_support::*;")?; writeln!(file_out, "")?; let state = PrintState::new(); writeln!(file_out, "{}", print_item_list(state, &v.items, true))?; } } } ...
{ writeln!(file_out, "pub mod {} {{", v.name.0.replace(".", "_"))?; writeln!(file_out, " use haskell_support::*;")?; writeln!(file_out, "")?; let state = PrintState::new(); writeln!(file_out, "{}", print_item_list(sta...
conditional_block
bgs-utils.ts
CardIds.SpiritRaptor_BG22_HERO_001_Buddy, CardIds.RagingContender_TB_BaconShop_HERO_67_Buddy, CardIds.CaptainFairmount_BG21_HERO_000_Buddy, CardIds.FlightTrainer_BG20_HERO_283_Buddy, CardIds.JandicesApprentice_TB_BaconShop_HERO_71_Buddy, CardIds.CrimsonHandCenturion_TB_BaconShop_HERO_60_Buddy, CardIds.CrazyMonke...
export const NON_DISCOVERABLE_BUDDIES = [
random_line_split
make_final_plot.py
def load_blacklist(experiment): """ Load event numbers from the blacklist file for each experiment and return them as an array """ blacklist = np.loadtxt('../Slip_Property_Data/%s_blacklist.txt'%experiment) return blacklist def load_events(experiment): """ Loads all events from a give...
""" Load event property file picks for a given experiment number and return that data as an array """ return np.loadtxt('../Slip_Property_Data/%s_event_properties.txt'%experiment,delimiter=',',skiprows=1)
identifier_body
make_final_plot.py
/$\mu$m]x1000""",fontsize=18) ax2.tick_params(axis='both', which='major', labelsize=16) ax2.get_yaxis().set_ticks([0,0.5,1,1.5,2,2.5,3,3.5]) ax2.text(-0.1,0.9,'B',transform = ax2.transAxes,fontsize=24) # Turns off chart clutter # Turn off top and right tick marks #ax2.get_xaxis().tick_bottom() #ax2.get_yaxis().tick_...
random_line_split
make_final_plot.py
(experiment): """ Load event property file picks for a given experiment number and return that data as an array """ return np.loadtxt('../Slip_Property_Data/%s_event_properties.txt'%experiment,delimiter=',',skiprows=1) def load_blacklist(experiment): """ Load event numbers from the blacklis...
load_event_properties
identifier_name
make_final_plot.py
print bin_steps[:,2] return disp_means,amb_means # These are the "Tableau 20" colors as RGB. tableau20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120), (44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150), (148, 103, 189), (197, 176, 213), (140, 86, 75)...
disp_means.append(np.mean(bin_steps[:,0])) amb_means.append(np.mean(bin_steps[:,1])) #amb_means.append(np.median(bin_steps[:,1]))
conditional_block
process.go
) IsReadOnly() bool { return p.Child().IsReadOnly() } // WithChildren implements the Node interface. func (p *QueryProcess) WithChildren(children ...sql.Node) (sql.Node, error) { if len(children) != 1 { return nil, sql.ErrInvalidChildrenNumber.New(p, len(children), 1) } return NewQueryProcess(children[0], p.Not...
() { if i.onDone != nil { i.onDone() i.onDone = nil } if i.node != nil { i.Dispose() i.node = nil } } func disposeNode(n sql.Node) { transform.Inspect(n, func(node sql.Node) bool { sql.Dispose(node) return true }) transform.InspectExpressions(n, func(e sql.Expression) bool { sql.Dispose(e) retur...
done
identifier_name
process.go
func (p *QueryProcess) IsReadOnly() bool { return p.Child().IsReadOnly() } // WithChildren implements the Node interface. func (p *QueryProcess) WithChildren(children ...sql.Node) (sql.Node, error) { if len(children) != 1 { return nil, sql.ErrInvalidChildrenNumber.New(p, len(children), 1) } return NewQueryProc...
}
random_line_split
process.go
IsReadOnly() bool { return p.Child().IsReadOnly() } // WithChildren implements the Node interface. func (p *QueryProcess) WithChildren(children ...sql.Node) (sql.Node, error) { if len(children) != 1 { return nil, sql.ErrInvalidChildrenNumber.New(p, len(children), 1) } return NewQueryProcess(children[0], p.Noti...
// CollationCoercibility implements the interface sql.CollationCoercible. func (p *QueryProcess) CollationCoercibility(ctx *sql.Context) (collation sql.CollationID, coercibility byte) { return sql.GetCoercibility(ctx, p.Child()) } func (p *QueryProcess) String() string { return p.Child().String() } func (p *QueryP...
{ return p.Child().CheckPrivileges(ctx, opChecker) }
identifier_body
process.go
IsReadOnly() bool { return p.Child().IsReadOnly() } // WithChildren implements the Node interface. func (p *QueryProcess) WithChildren(children ...sql.Node) (sql.Node, error) { if len(children) != 1 { return nil, sql.ErrInvalidChildrenNumber.New(p, len(children), 1) } return NewQueryProcess(children[0], p.Noti...
if i.node != nil { i.Dispose() i.node = nil } } func disposeNode(n sql.Node) { transform.Inspect(n, func(node sql.Node) bool { sql.Dispose(node) return true }) transform.InspectExpressions(n, func(e sql.Expression) bool { sql.Dispose(e) return true }) } func (i *trackedRowIter) Dispose() { if i.no...
{ i.onDone() i.onDone = nil }
conditional_block
peer.go
func strToPeerId(str string) PeerId { parts := strings.Split(str, ":") return PeerId{ Address: parts[0], Port: strToInt(parts[1]), } } /* * Represents another peer, storing information about * the other peer as necessary, and handling requests/actions * involving that other peer (storeShard, etc.) * *...
{ return fmt.Sprintf("%s:%d", this.Address, this.Port) }
identifier_body
peer.go
// cached values localUsedBytes int remoteUsedBytes int lastVerifyTime time.Time // last time we performed a shard storage verification lastVerifySuccessTime time.Time verifyFailCount int // count of successive verification failures // set of shards that we have accounted for in the cached remoteUsedBytes //...
} } func (this *Peer) getShardPath(label int64) string { // todo: make the store directory automatically return fmt.Sprintf("store/%s_%d.obj", this.id.String(), label) } /* * called on a representation * to say that the peer it represents is trying to * store data on our peer */ func (this *Peer) eventStoreSha...
return false
random_line_split
peer.go
// cached values localUsedBytes int remoteUsedBytes int lastVerifyTime time.Time // last time we performed a shard storage verification lastVerifySuccessTime time.Time verifyFailCount int // count of successive verification failures // set of shards that we have accounted for in the cached remoteUsedBytes // ...
this.shardsAccounted[shard.Id] = true result := this.protocol.storeShard(this.id, int64(shard.Id), shard.Contents) if result == 0 { return true } else if result == -2 { // peer actively refused the shard! // probably the agreement is not synchronized or peer terminated agreement go this.terminateAgreemen...
{ // this is bad, blockstore is trying to store a shard that hasn't been reserved yet? Log.Error.Printf("Peer handler %s received unaccounted shard %d!", this.id.String(), shard.Id) return false }
conditional_block
peer.go
// cached values localUsedBytes int remoteUsedBytes int lastVerifyTime time.Time // last time we performed a shard storage verification lastVerifySuccessTime time.Time verifyFailCount int // count of successive verification failures // set of shards that we have accounted for in the cached remoteUsedBytes // ...
(localBytes int, remoteBytes int) { this.mu.Lock() this.localBytes += localBytes this.remoteBytes += remoteBytes Log.Debug.Printf("New agreement with %s (%d to %d; total %d/%d to %d/%d)", this.id.String(), localBytes, remoteBytes, this.localUsedBytes, this.localBytes, this.remoteUsedBytes, this.remoteBytes) this.m...
eventAgreement
identifier_name
TelephonyBaseTest.py
.controllers.diag_logger from acts.base_test import BaseTestClass from acts.keys import Config from acts.signals import TestSignal from acts.signals import TestAbortClass from acts.signals import TestAbortAll from acts import utils from acts.test_utils.tel.tel_subscription_utils import \ initial_set_up_for_subid_...
ad.log.info("Enter PUK code and pin") if not ad.droid.telephonySupplyPuk(ad.puk, ad.puk_pin): abort_all_tests( ad.log, "Puk and puk_pin provided in testbed config do NOT work" ) self.skip_re...
abort_all_tests(ad.log, "puk_pin is not provided")
conditional_block
TelephonyBaseTest.py
.controllers.diag_logger from acts.base_test import BaseTestClass from acts.keys import Config from acts.signals import TestSignal from acts.signals import TestAbortClass from acts.signals import TestAbortAll from acts import utils from acts.test_utils.tel.tel_subscription_utils import \ initial_set_up_for_subid_...
# Use for logging in the test cases to facilitate # faster log lookup and reduce ambiguity in logging. @staticmethod def tel_test_wrap(fn): def _safe_wrap_test_case(self, *args, **kwargs): test_id = "%s:%s:%s" % (self.__class__.__name__, self.test_name, ...
"Puk and puk_pin provided in testbed config do NOT work" ) self.skip_reset_between_cases = self.user_params.get( "skip_reset_between_cases", True)
random_line_split
TelephonyBaseTest.py
_utils.tel.tel_defines import PRECISE_CALL_STATE_LISTEN_LEVEL_RINGING from acts.test_utils.tel.tel_defines import WIFI_VERBOSE_LOGGING_ENABLED from acts.test_utils.tel.tel_defines import WIFI_VERBOSE_LOGGING_DISABLED from acts.utils import force_airplane_mode QXDM_LOG_PATH = "/data/vendor/radio/diag_logs/logs/" clas...
if getattr(self, "diag_logger", None): for logger in self.diag_logger: self.log.info("Starting a diagnostic session %s", logger) self.logger_sessions.append((logger, logger.start())) if self.skip_reset_between_cases: ensure_phones_idle(self.log, self.andr...
identifier_body
TelephonyBaseTest.py
.controllers.diag_logger from acts.base_test import BaseTestClass from acts.keys import Config from acts.signals import TestSignal from acts.signals import TestAbortClass from acts.signals import TestAbortAll from acts import utils from acts.test_utils.tel.tel_subscription_utils import \ initial_set_up_for_subid_...
(self, *args, **kwargs): test_id = "%s:%s:%s" % (self.__class__.__name__, self.test_name, self.begin_time.replace(' ', '-')) self.test_id = test_id log_string = "[Test ID] %s" % test_id self.log.info(log_string) try: ...
_safe_wrap_test_case
identifier_name
reader.go
poll. addr gospel.Address // globalLimit is a rate-limiter that limits the number of polling queries // that can be performed each second. It is shared by all readers, and hence // provides a global cap of the number of read queries per second. globalLimit *rate.Limiter // adaptiveLimit is a rate-limiter that ...
done: make(chan error, 1), ctx: runCtx, cancel: cancel, addr: addr, globalLimit: limit, adaptiveLimit: rate.NewLimiter(rate.Every(accetableLatency), 1), acceptableLatency: accetableLatency, starvationLatency: getStarvationLatency(opts), aver...
r := &Reader{ logger: logger, facts: make(chan gospel.Fact, getReadBufferSize(opts)), end: make(chan struct{}),
random_line_split
reader.go
poll. addr gospel.Address // globalLimit is a rate-limiter that limits the number of polling queries // that can be performed each second. It is shared by all readers, and hence // provides a global cap of the number of read queries per second. globalLimit *rate.Limiter // adaptiveLimit is a rate-limiter that ...
() (int, error) { rows, err := r.stmt.QueryContext( r.ctx, r.addr.Offset, ) if err != nil {
poll
identifier_name
reader.go
poll. addr gospel.Address // globalLimit is a rate-limiter that limits the number of polling queries // that can be performed each second. It is shared by all readers, and hence // provides a global cap of the number of read queries per second. globalLimit *rate.Limiter // adaptiveLimit is a rate-limiter that ...
} if logger.IsDebug() { r.debug = &readerDebug{ opts: opts, averagePollRate: metrics.NewRateCounter(), averageFactRate: metrics.NewRateCounter(), } } if err := r.prepareStatement(ctx, db, storeID, opts); err != nil { return nil, err } r.logInitialization() go r.run() return r, nil...
{ // Note that runCtx is NOT derived from ctx, which is only used for the // opening of the reader itself. runCtx, cancel := context.WithCancel(context.Background()) accetableLatency := getAcceptableLatency(opts) r := &Reader{ logger: logger, facts: make(chan gospel.Fact, getReadBuffer...
identifier_body
reader.go
available, return with ok == false return case <-ctx.Done(): err = ctx.Err() return case err = <-r.done: if err == nil { err = errReaderClosed } return } } else { r.current = r.next r.next = nil ok = true } // Perform a non-blocking lookahead to see if we have the next fact alread...
return fmt.Sprintf("%6.02fm ", d.Seconds()/60) }
conditional_block
CaptureGridView.js
, 'reset', this.render); return this; }, render: function () { this.ro = this.getRenderObject(); this.$el.html(this.compiledTemplate(this.ro)); this.renderGrid(); this.renderItemViews(); return this; }, getRenderObject: function () { var ro = { ...
editString += '</div>'; var $dlg; var that = this; var okFunc = function (cleanupFunc) { var $editElements = $dlg.find('.searchColumnEdit input, .searchColumnEdit select'); var value = that.applyColumnEdit(cleanupFunc, selected, columnId, $e...
if (this.captureGridItemViews[i].model === selected[0]) { editString += this.captureGridItemViews[i].getFieldEditObject(columnId, ['']); break; } }
conditional_block
CaptureGridView.js
.collection, 'reset', this.render); return this; }, render: function () { this.ro = this.getRenderObject(); this.$el.html(this.compiledTemplate(this.ro)); this.renderGrid(); this.renderItemViews(); return this; }, getRenderObject: function () { var...
if
//Loop preference adding back values from exising preferences that are not specified while still dropping columns no longer displayed. (no extend). var id; var totWidth = 0; for (id in preference) { if (preference.hasOwnProperty(id)) {
random_line_split
pix2pix_sat_imgs.py
, use_bn=True): super(EncoderUnit, self).__init__() self.conv_layer1 = nn.Conv2d(input_channels, input_channels * 2,kernel_size=3,padding=1) self.conv_layer2 = nn.Conv2d(input_channels * 2, input_channels * 2, kernel_size=3, padding=1) self.act_function= nn.LeakyReLU(0.2) self.po...
center_height = image.shape[2] // 2 center_width = image.shape[3] // 2 top_left = center_height - round(target_shape[2] / 2) top_right = top_left + target_shape[2] bottom_left = center_width - round(target_shape[3] / 2) bottom_right = bottom_left + target_shape[3] self.new_imag...
return decoded_fm def crop_image(self, image, target_shape):
random_line_split
pix2pix_sat_imgs.py
([input_fm, cropped_input_fm ], axis=1) decoded_fm = self.conv_layer2(out_fm) if self.use_bn: decoded_fm = self.bn(decoded_fm) if self.use_dropout: decoded_fm = self.dropout(decoded_fm) decoded_fm = self.act_function(decoded_fm) decoded_fm = self.conv_laye...
if cur_step > 0: print(f"Epoch {epoch}: Step {cur_step}: Generator (U-Net) loss: {mean_generator_loss}, Discriminator loss: {mean_discriminator_loss}") else: print("Pretrained initial state") plot_images(condition, size=(input_img_channels, target_shape, target_sh...
conditional_block
pix2pix_sat_imgs.py
, use_bn=True): super(EncoderUnit, self).__init__() self.conv_layer1 = nn.Conv2d(input_channels, input_channels * 2,kernel_size=3,padding=1) self.conv_layer2 = nn.Conv2d(input_channels * 2, input_channels * 2, kernel_size=3, padding=1) self.act_function= nn.LeakyReLU(0.2) self.po...
(self, input_fm): out = self.conv_layer1(input_fm) if self.use_bn: out = self.bn(out) if self.use_dropout: out = self.dropout(out) out = self.act_function(out) out = self.conv_layer2(out) if self.use_bn: out = self.bn(out) if se...
forward
identifier_name
pix2pix_sat_imgs.py
, use_bn=True):
def forward(self, input_fm): out = self.conv_layer1(input_fm) if self.use_bn: out = self.bn(out) if self.use_dropout: out = self.dropout(out) out = self.act_function(out) out = self.conv_layer2(out) if self.use_bn: out = self.bn(o...
super(EncoderUnit, self).__init__() self.conv_layer1 = nn.Conv2d(input_channels, input_channels * 2,kernel_size=3,padding=1) self.conv_layer2 = nn.Conv2d(input_channels * 2, input_channels * 2, kernel_size=3, padding=1) self.act_function= nn.LeakyReLU(0.2) self.pooling_layer = nn.MaxPool...
identifier_body
exec.rs
or more regular expressions, capture groups /// are completely unsupported. (This means both `find` and `captures` /// wont work.) pub fn new_many<I, S>(res: I) -> Self where S: AsRef<str>, I: IntoIterator<Item=S> { let mut opts = RegexOptions::default(); opts.pats = res.into_it...
/// /// This overrides whatever was previously set via the `nfa` or /// `bounded_backtracking` methods. pub fn automatic(mut self) -> Self { self.match_type = None; self } /// Sets the matching engine to use the NFA algorithm no matter what /// optimizations are possible. ...
random_line_split
exec.rs
<'c>(ExecNoSync<'c>); /// `ExecReadOnly` comprises all read only state for a regex. Namely, all such /// state is determined at compile time and never changes during search. #[derive(Debug)] struct ExecReadOnly { /// The original regular expressions given by the caller to compile. res: Vec<String>, /// A c...
ExecNoSyncStr
identifier_name
exec.rs
more regular expressions, capture groups /// are completely unsupported. (This means both `find` and `captures` /// wont work.) pub fn new_many<I, S>(res: I) -> Self where S: AsRef<str>, I: IntoIterator<Item=S> { let mut opts = RegexOptions::default(); opts.pats = res.into_iter(...
#[inline(always)] // reduces constant overhead fn is_match_at(&self, text: &str, start: usize) -> bool { self.0.is_match_at(text.as_bytes(), start) } #[inline(always)] // reduces constant overhead fn find_at(&self, text: &str, start: usize) -> Option<(usize, usize)> { self.0.find_...
{ self.0.shortest_match_at(text.as_bytes(), start) }
identifier_body
blob_store.rs
_data_len: uint, max_blob_size: uint, } fn empty_blob_desc() -> blob_index::BlobDesc { blob_index::BlobDesc{name: b"".into_vec(), id: 0} } impl <B: BlobStoreBackend> BlobStore<B> { pub fn new(index: BlobIndexProcess, backend: B, max_blob_size: uint) -> BlobStore<B> { let mut bs = BlobStore{...
{ fn prop(chunks: Vec<Vec<u8>>) -> bool { let mut backend = MemoryBackend::new(); let local_backend = backend.clone(); let bsP: BlobStoreProcess<MemoryBackend> = Process::new(proc() { BlobStore::new_for_testing(local_backend, 1024) }); let mut ids = Vec::new(); for chunk in c...
identifier_body
blob_store.rs
self, name: &Vec<u8>) -> Option<Result<Vec<u8>, String>> { self.read_cache.lock().get(name).map(|v| v.clone()) } fn guarded_cache_put(&mut self, name: Vec<u8>, result: Result<Vec<u8>, String>) { self.read_cache.lock().put(name, result); } } impl BlobStoreBackend for FileBackend { fn store(&mut self, ...
() -> blob_index::BlobDesc { blob_index::BlobDesc{name: b"".into_vec(), id: 0} } impl <B: BlobStoreBackend> BlobStore<B> { pub fn new(index: BlobIndexProcess, backend: B, max_blob_size: uint) -> BlobStore<B> { let mut bs = BlobStore{ backend: backend, blob_index: index, blob_de...
empty_blob_desc
identifier_name
blob_store.rs
(&self, name: &Vec<u8>) -> Option<Result<Vec<u8>, String>> { self.read_cache.lock().get(name).map(|v| v.clone()) } fn guarded_cache_put(&mut self, name: Vec<u8>, result: Result<Vec<u8>, String>) { self.read_cache.lock().put(name, result); } } impl BlobStoreBackend for FileBackend { fn store(&mut self...
}, None => break, } } self.blob_index.send_reply(blob_index::InAir(old_blob_desc.clone())); self.backend_store(old_blob_desc.name.as_slice(), blob.as_slice()); self.blob_index.send_reply(blob_index::CommitDone(old_blob_desc)); // Go through callbacks for (blobid, cb) in r...
blob.push_all(chunk.as_slice());
random_line_split
input_loop.go
/tracking" "github.com/AljabrIO/koalja-operator/pkg/util/retry" "github.com/dchest/uniuri" ) // inputLoop subscribes to all inputs of a task and build // snapshots of incoming annotated values, according to the policy on each input. type inputLoop struct { log zerolog.Logger spec *koalja.Tas...
else if err != nil { il.log.Error().Err(err).Msg("Failed to execute task") } }() } else if il.spec.HasLaunchPolicyCustom() { // Custom launch policy; Make snapshot available to snapshot service if err := il.snapshotService.Execute(ctx, snapshot); ctx.Err() != nil { return ctx.Err() } ...
// Context canceled, ignore }
conditional_block
input_loop.go
/pkg/tracking" "github.com/AljabrIO/koalja-operator/pkg/util/retry" "github.com/dchest/uniuri" ) // inputLoop subscribes to all inputs of a task and build // snapshots of incoming annotated values, according to the policy on each input. type inputLoop struct { log zerolog.Logger spec *koalja...
return il.processExecQueue(lctx) }) if err := g.Wait(); err != nil { return err } return nil } // processExecQueue pulls snapshots from the exec queue and: // - executes them in case of tasks with auto launch policy or // - allows the executor to pull the snapshot in case of tasks with custom launch policy. fu...
defer close(il.execQueue) g, lctx := errgroup.WithContext(ctx) if len(il.spec.Inputs) > 0 { // Watch inputs for _, tis := range il.spec.Inputs { tis := tis // Bring in scope stats := il.statistics.InputByName(tis.Name) g.Go(func() error { return il.watchInput(lctx, il.spec.SnapshotPolicy, tis, stat...
identifier_body
input_loop.go
/pkg/tracking" "github.com/AljabrIO/koalja-operator/pkg/util/retry" "github.com/dchest/uniuri" ) // inputLoop subscribes to all inputs of a task and build // snapshots of incoming annotated values, according to the policy on each input. type inputLoop struct { log zerolog.Logger spec *koalja...
// Run the input loop until the given context is canceled. func (il *inputLoop) Run(ctx context.Context) error { defer close(il.execQueue) g, lctx := errgroup.WithContext(ctx) if len(il.spec.Inputs) > 0 { // Watch inputs for _, tis := range il.spec.Inputs { tis := tis // Bring in scope stats := il.statisti...
}, nil }
random_line_split
input_loop.go
/tracking" "github.com/AljabrIO/koalja-operator/pkg/util/retry" "github.com/dchest/uniuri" ) // inputLoop subscribes to all inputs of a task and build // snapshots of incoming annotated values, according to the policy on each input. type inputLoop struct { log zerolog.Logger spec *koalja.Tas...
ctx context.Context, snapshot *InputSnapshot) error { // Update statistics atomic.AddInt64(&il.statistics.SnapshotsWaiting, -1) atomic.AddInt64(&il.statistics.SnapshotsInProgress, 1) snapshot.AddInProgressStatistics(1) // Update statistics on return defer func() { snapshot.AddInProgressStatistics(-1) snapsho...
xecOnSnapshot(
identifier_name
Confess.js
still view the confessional but will be unable to confess.', tx: null, tetzelInstance: null, tetzelAddress: 'Loading...', tetzelCoinAddress: 'Loading...', account: 'Loading...', sinText: '', sinValueUSD: 0, sinValueETH: 0, sinRate: 500, sinRecipient: '', ...
changeActiveView(nextView) { const validViews = ['CONFESS_SIN', 'VALUE_SIN', 'PURCHASE_SIN', 'FORGIVENESS']; if (validViews.indexOf(nextView) === -1) { throw new Error('Invalid view'); } // Validating sin text input shouldn't have to occur here, but it does // with the way this is currently...
random_line_split
Confess.js
view the confessional but will be unable to confess.', tx: null, tetzelInstance: null, tetzelAddress: 'Loading...', tetzelCoinAddress: 'Loading...', account: 'Loading...', sinText: '', sinValueUSD: 0, sinValueETH: 0, sinRate: 500, sinRecipient: '', test...
handleInvalidSinText() { this.setState({errorMsg: 'Please confess before moving on.'}); } updateTestSinValues(idx, val) { var newTestSinValues = this.state.testSinValues.slice(); newTestSinValues[idx] = val; this.setState({testSinValues: newTestSinValues}); } updateSinRecipient(val) { ...
{ return this.state.sinText.length > 0; }
identifier_body
Confess.js
still view the confessional but will be unable to confess.', tx: null, tetzelInstance: null, tetzelAddress: 'Loading...', tetzelCoinAddress: 'Loading...', account: 'Loading...', sinText: '', sinValueUSD: 0, sinValueETH: 0, sinRate: 500, sinRecipient: '', ...
() { const showActiveView = () => { switch(this.state.activeView) { case 'CONFESS_SIN': return ( <ConfessSin errorMsg={ this.state.errorMsg } sinText={ this.state.sinText } updateSinText={ this.updateSinText.bind(this) } on...
render
identifier_name
mod.rs
/// this function will return vector with only one animation. fn retarget_animations_directly(&self, root: Handle<Node>, graph: &Graph) -> Vec<Animation>; /// Tries to retarget animations from given model resource to a node hierarchy starting /// from `root` on a given scene. Unlike [`Self::retarget_anima...
Self::MaterialsDirectory(path.as_ref().to_path_buf()) } }
random_line_split
mod.rs
handle: Handle<Node>, dest_graph: &mut Graph, ) -> (Handle<Node>, NodeHandleMap) { let (root, old_to_new) = model_data .scene .graph .copy_node(handle, dest_graph, &mut |_, _| true); // Notify instantiated nodes about resource the...
{ write!(f, "An error occurred while reading a data source {v:?}") }
conditional_block
mod.rs
Reset resource instance root flag, this is needed because a node after instantiation cannot // be a root anymore. node.is_resource_instance_root = false; // Reset inheritable properties, so property inheritance system will take properties // from parent objects on resol...
{ ModelLoadError::Visit(e) }
identifier_body