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
sampleMultiMCTSAgentTrajectory.py
.isTerminal, self.getStateFromNode, approximateValue) guidedMCTSPolicy = MCTS(self.numSimulations, self.selectChild, expand, estimateValue, backup, establishPlainActionDist) return guidedMCTSPolicy class PrepareMultiAgentPolicy: def __init__(self, composeSingleAgen...
modelPath = generateNNModelSavePath({'iterationIndex': iterationIndex, 'agentId': agentId}) restoredNNModel = restoreVariables(multiAgentNNmodel[agentId], modelPath) multiAgentNNmodel[agentId] = restoredNNModel
conditional_block
sampleMultiMCTSAgentTrajectory.py
Buffer import SampleBatchFromBuffer, SaveToBuffer from exec.preProcessing import AccumulateMultiAgentRewards, AddValuesToTrajectory, RemoveTerminalTupleFromTrajectory, \ ActionToOneHot, ProcessTrajectoryForPolicyValueNet from src.algorithms.mcts import ScoreChild, SelectChild, InitializeChildren, Expand, MCTS, back...
numAgents = 2 qVelInitNoise = 8 qPosInitNoise = 9.7 reset = ResetUniform(physicsSimulation, qPosInit, qVelInit, numAgents, qPosInitNoise, qVelInitNoise) agentIds = list(range(numAgents)) sheepId = 0 wolfId = 1 xPosIndex = [2, 3] getSheepXPos = Get...
random_line_split
ballot.rs
ism. #[serde(default)] #[serde(skip_serializing_if = "IndexMap::is_empty")] pub properties: IndexMap<String, serde_json::Value>, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Contest { pub id: String, pub index: u32, pub contest_type: ContestType, pub num_winners: u32, p...
#[serde(default)] pub write_in: bool, /// Score has different meanings depending on the tally type: /// STV, Condorcet, Borda and Schulze: `score` means candidate rank, where a zero is the best rank that can be assigned to a candidate. /// Score: `score` is the points assinged to this candidate.
#[derive(Serialize, Deserialize, Clone, Message, PartialEq, Eq)] pub struct Selection { /// true if the `selection` field is a free-form write-in, false if the `selection` field corresponds to a known candidate-id #[prost(bool)]
random_line_split
ballot.rs
{ pub id: String, pub contests: Vec<u32>, // List of contest indexes /// Application specific properties. /// /// Hashmaps are not allowed because their unstable ordering leads to non-determinism. #[serde(default)] #[serde(skip_serializing_if = "IndexMap::is_empty")] pub properties: In...
Ballot
identifier_name
universe.rs
but safely because all of the data is atomic. /// /// The [`Poe`](crate::Poe) struct exposes some of these settings — start/stop, /// audio, speed — to the end user, but the rest are fully closed off. pub(crate) struct Universe; impl Universe { const ACTIVE: u8 = 0b0000_0001; // Poe is active. const AUDIO: u...
[cfg(feature = "firefox")] /// # Fix Element Bindings? /// /// Returns `true` if one or both elements seem to have disappeared from /// the document body since the last time this method was called. pub(crate) fn fix_bindings() -> bool { let old = FLAGS.fetch_and(! Self::FIX_BINDINGS, SeqCst); let expected = Se...
let old = FLAGS.fetch_and(! Self::ASSIGN_CHILD, SeqCst); Self::ASSIGN_CHILD == old & Self::ASSIGN_CHILD } #
identifier_body
universe.rs
but safely because all of the data is atomic. /// /// The [`Poe`](crate::Poe) struct exposes some of these settings — start/stop, /// audio, speed — to the end user, but the rest are fully closed off. pub(crate) struct Universe; impl Universe { const ACTIVE: u8 = 0b0000_0001; // Poe is active. const AUDIO: u...
> bool { let old = FLAGS.fetch_and(! Self::ASSIGN_CHILD, SeqCst); Self::ASSIGN_CHILD == old & Self::ASSIGN_CHILD } #[cfg(feature = "firefox")] /// # Fix Element Bindings? /// /// Returns `true` if one or both elements seem to have disappeared from /// the document body since the last time this method was cal...
gn_child() -
identifier_name
universe.rs
) -> bool { if v == (0 != FLAGS.load(SeqCst) & (Self::ACTIVE | Self::STATE)) { false } else { if v { // Set active flag. FLAGS.fetch_or(Self::ACTIVE, SeqCst); // Seed future randomness if we can. #[cfg(target_arch = "wasm32")] reseed(); // Set up the DOM elements and event bindings, and beg...
use super::*; use std::collections::HashSet; #[test] fn t_rand() {
random_line_split
visual_functions-checkpoint.py
): """ Returns subplots with an appropriate figure size and tight layout. """ fig_width, fig_height = get_width_height(fig_width, fig_height, columns=2) fig, axes = plt.subplots(figsize=(fig_width, fig_height), *args, **kwargs) return fig, axes def legend(ax, ncol=3, loc=9, pos=(0.5, -0.1)): ...
OFFSET = -0.7 plt.text(av-5,OFFSET,b,color='darkorange')
conditional_block
visual_functions-checkpoint.py
ettle','Fan','AC','HairIron','LaptopCharger','SolderingIron','Fridge','Vacuum','CoffeeMaker','FridgeDefroster'] lilac_labels={'1-phase-async-motor':"1P-Motor", '3-phase-async-motor':"3P-Motor", 'Bulb':"ILB", 'Coffee-machine':"CM", 'Drilling-machine':"DRL", 'Dumper-machine':"3P-DPM", 'Fluorescent-lamp':"CF...
(ax): for spine in ['top', 'right']: ax.spines[spine].set_visible(False) for spine in ['left', 'bottom']: ax.spines[spine].set_color(SPINE_COLOR) ax.spines[spine].set_linewidth(0.5) ax.yaxis.set_ticks_position('left') ax.xaxis.set_ticks_position('bottom')...
format_axes
identifier_name
visual_functions-checkpoint.py
ettle','Fan','AC','HairIron','LaptopCharger','SolderingIron','Fridge','Vacuum','CoffeeMaker','FridgeDefroster'] lilac_labels={'1-phase-async-motor':"1P-Motor", '3-phase-async-motor':"3P-Motor", 'Bulb':"ILB", 'Coffee-machine':"CM", 'Drilling-machine':"DRL", 'Dumper-machine':"3P-DPM", 'Fluorescent-lamp':"CF...
a = '{0:0.02f}'.format(av) b = '$Fmacro =\ $'+a if av > 75: plt.text(av-27,0.1,b,color='darkorange') else: plt.text(av+2,0
av = 0 p = [] for i in range(len(n)): teller = 2 * cm[i,i] noemer = sum(cm[:,i]) + sum(cm[i,:]) F = float(teller) / float(noemer) av += F #print('{0} {1:.2f}'.format(names[i],F*100)) p.append(F*100) av = av/len(n)*100 p = np.array(p) volgorde = n...
identifier_body
visual_functions-checkpoint.py
ettle','Fan','AC','HairIron','LaptopCharger','SolderingIron','Fridge','Vacuum','CoffeeMaker','FridgeDefroster'] lilac_labels={'1-phase-async-motor':"1P-Motor", '3-phase-async-motor':"3P-Motor", 'Bulb':"ILB", 'Coffee-machine':"CM", 'Drilling-machine':"DRL", 'Dumper-machine':"3P-DPM", 'Fluorescent-lamp':"CF...
volgorde = np.argsort(p) fig, ax = plt.subplots(figsize=(6, 5)) sns.set_color_codes("pastel") sns.barplot(x=p[volgorde], y=np.array(n)[volgorde], color='b') plt.axvline(x=av,color='orange', linewidth=1.0, linestyle="--") a = '{0:0.02f}'.format(av) b = '$Fmacro =\ $'+a i...
p.append(F*100) av = av/len(n)*100 p = np.array(p)
random_line_split
lib.rs
& !registers::PaLevel::Pa2_On, } } } #[allow(dead_code)] enum AddressFiltering { None, AddressOnly(u8), AddressOrBroadcast((u8,u8)), //(addr, broadcast_addr) } #[allow(dead_code)] #[derive(Debug, PartialEq, Clone, Copy)] enum RadioMode { //rename transeiver? Sleep = 0, // Xtal Off Standby = 1, // Xt...
(&mut self) -> Result<(),&'static str> { //self.cs.set_high(); //check if the radio responds by seeing if we can change a register let mut synced = false; for _attempt in 0..100 { self.write_reg(Register::Syncvalue1, 0xAA); //170 self.delay.delay_ms(1); if self.read_reg(Register::Syncvalue1) == 0xAA {...
init
identifier_name
lib.rs
Some(mut key) => { self.register_flags.config2 |= registers::PacketConfig2::Aes_On; //set aes on key[0] = Register::Aeskey1.write_address(); self.spi.write(&key).unwrap(); }, } self.delay.delay_us(15u16); self.write_reg(Register::Packetconfig2, self.register_flags.config2.bits()); self.sw...
{ if !self.register_flags.mode.contains(registers::OpMode::Sequencer_Off) { self.register_flags.mode |= registers::OpMode::Sequencer_Off; self.write_reg(Register::Opmode, self.register_flags.mode.bits()); self.switch_freq()?; self.register_flags.mode -= registers::OpMode::Sequencer_Off; self.wr...
identifier_body
lib.rs
_On & !registers::PaLevel::Pa2_On, } } } #[allow(dead_code)] enum AddressFiltering { None, AddressOnly(u8), AddressOrBroadcast((u8,u8)), //(addr, broadcast_addr) } #[allow(dead_code)] #[derive(Debug, PartialEq, Clone, Copy)] enum RadioMode { //rename transeiver? Sleep = 0, // Xtal Off Standby = 1, //...
//self.cs.set_high(); //check if the radio responds by seeing if we can change a register let mut synced = false; for _attempt in 0..100 { self.write_reg(Register::Syncvalue1, 0xAA); //170 self.delay.delay_ms(1); if self.read_reg(Register::Syncvalue1) == 0xAA { synced = true; break; } } ...
random_line_split
http_service_util.rs
url_string: S) -> http::UrlRequest { http::UrlRequest { url: url_string.to_string(), method: String::from("GET"), headers: None, body: None, response_body_buffer_size: 0, auto_follow_redirects: true, cache_mode: http::CacheMode::Default, response_body_...
#[test] fn zero_byte_download_triggers_error() { let test_url = "https://test.example/sample/url"; let url_req = create_url_request(test_url.to_string()); // creating a response with some bytes "downloaded" let bytes = "".as_bytes(); let (s1, s2) = zx::Socket::create(z...
{ let test_url = "https://test.example/sample/url"; let url_req = create_url_request(test_url.to_string()); // creating a response with some bytes "downloaded" let bytes = "there are some bytes".as_bytes(); let (s1, s2) = zx::Socket::create(zx::SocketOpts::STREAM).unwrap(); ...
identifier_body
http_service_util.rs
url_string: S) -> http::UrlRequest { http::UrlRequest { url: url_string.to_string(), method: String::from("GET"), headers: None, body: None, response_body_buffer_size: 0, auto_follow_redirects: true, cache_mode: http::CacheMode::Default, response_body_...
( request: UrlRequest, mut response: UrlResponse, ) -> Result<IndividualDownload, Error> { let mut exec = fasync::Executor::new().expect("failed to create an executor"); let (http_service, server) = create_http_service_util(); let mut next_http_service_req = server.into_futur...
trigger_download_with_supplied_response
identifier_name
http_service_util.rs
url_string: S) -> http::UrlRequest { http::UrlRequest { url: url_string.to_string(), method: String::from("GET"), headers: None, body: None, response_body_buffer_size: 0,
// Object to hold results of a single download #[derive(Default)] pub struct IndividualDownload { pub bytes: u64, pub nanos: u64, pub goodput_mbps: f64, } // TODO (NET-1664): verify checksum on data received pub async fn fetch_and_discard_url( http_service: &HttpServiceProxy, mut url_request: http...
auto_follow_redirects: true, cache_mode: http::CacheMode::Default, response_body_mode: http::ResponseBodyMode::Stream, } }
random_line_split
sumtree.rs
{ self.root = Some(NodeData { full: true, node: Node::Leaf(elem_sum), hash: elem_hash, depth: 0, }); self.index.insert(index_hash, 0); return true; } // Next, move the old root out of the structure so that we are allowed to // move it. We will move a new root back in at the end of th...
(node: &NodeData<T>) -> NodeData<T> { if node.full { // replaces full internal nodes, leaves and already pruned nodes are full // as well NodeData { full: true, node: Node::Pruned(node.sum()), hash: node.hash, depth: node.depth, } } else { if let Node::...
clone_pruned_recurse
identifier_name
sumtree.rs
, { // Read depth byte let depth = try!(reader.read_u8()); let full = depth & 0x80 == 0x80; let pruned = depth & 0xc0 != 0xc0; let depth = depth & 0x3f; // Sanity-check for zero byte if pruned && !full { return Err(ser::Error::CorruptedData); } // Read remainder of node let hash = try!(Readable::read(read...
TestElem([0, 0, 0, 2]),
random_line_split
ply.rs
{ format: Format, elements: Vec<Element>, offset: Vector3<f64>, } #[derive(Debug, Copy, Clone, PartialEq)] enum DataType { Int8, Uint8, Int16, Uint16, Int32, Uint32, Float32, Float64, } impl DataType { fn from_str(input: &str) -> Result<Self> { match input { ...
Header
identifier_name
ply.rs
Index<&'a str> for Header { type Output = Element; fn index(&self, name: &'a str) -> &Self::Output { for element in &self.elements { if element.name == name { return element; } } panic!("Element {} does not exist.", name); } } #[derive(Debug,...
create_and_return_reading_fn!($assign, $size, 8, LittleEndian::read_f64) } } }; } // Similar to 'create_and_return_reading_fn', but creates a function that just advances the read // pointer. macro_rules! create_skip_fn { (&mut $size:ident, $num_bytes:expr) => {{ $siz...
} DataType::Float64 => {
random_line_split
ply.rs
Index<&'a str> for Header { type Output = Element; fn index(&self, name: &'a str) -> &Self::Output { for element in &self.elements { if element.name == name { return element; } } panic!("Element {} does not exist.", name); } } #[derive(Debug,...
current_element.as_mut().unwrap().properties.push(property); } "end_header" => break, "comment" => { if entries.len() == 5 && entries[1] == "offset:" { let x = entries[2] .parse::<f64>() ...
{ if current_element.is_none() { return Err( InvalidInput(format!("property outside of element: {}", line)).into(), ); }; let property = match entries[1] { "list" if entries.len() == 5 => ...
conditional_block
CO542_project.py
1000 images split will 200 for testing validationRatio = 0.2 # if 1000 images 20% of remaining 800 will be 160 for validation ################################################### ############################### Importing of the Images count = 0 images = [] classNo = [] myList = os.listdir(path) print("Total Classes...
print(" ") images = np.array(images) classNo = np.array(classNo) ############################### Split Data X_train, X_test, y_train, y_test = train_test_split(images, classNo, test_size=testRatio) X_train, X_validation, y_train, y_validation = train_test_split(X_train, y_train, test_size=validationRatio) # X_train...
myPicList = os.listdir(path+"/"+str(count)) for y in myPicList: curImg = cv2.imread(path+"/"+str(count)+"/"+y) images.append(curImg) classNo.append(count) print(count, end =" ") count +=1
conditional_block
CO542_project.py
MORE GENERIC dataGen= ImageDataGenerator(width_shift_range=0.1, # 0.1 = 10% IF MORE THAN 1 E.G 10 THEN IT REFFERS TO NO. OF PIXELS EG 10 PIXELS height_shift_range=0.1, zoom_range=0.2, # 0.2 MEANS CAN GO FROM 0.8 TO 1.2 shear_ra...
equalize
identifier_name
CO542_project.py
1000 images split will 200 for testing validationRatio = 0.2 # if 1000 images 20% of remaining 800 will be 160 for validation ################################################### ############################### Importing of the Images count = 0 images = [] classNo = [] myList = os.listdir(path) print("Total Classes...
model.add((Conv2D(no_Of_Filters // 2, size_of_Filter2, activation='relu'))) model.add(MaxPooling2D(pool_size=size_of_pool)) model.add(Dropout(0.5)) model.add(Flatten()) model.add(Dense(no_Of_Nodes,activation='relu')) model.add(Dropout(0.5)) model.add(Dense(noOfClasses,activation='softmax')...
model.add((Conv2D(no_Of_Filters//2, size_of_Filter2,activation='relu')))
random_line_split
CO542_project.py
1000 images split will 200 for testing validationRatio = 0.2 # if 1000 images 20% of remaining 800 will be 160 for validation ################################################### ############################### Importing of the Images count = 0 images = [] classNo = [] myList = os.listdir(path) print("Total Classes...
def equalize(img): img =cv2.equalizeHist(img) return img def preprocessing(img): img = grayscale(img) # CONVERT TO GRAYSCALE img = equalize(img) # STANDARDIZE THE LIGHTING IN AN IMAGE img = img/255 # TO NORMALIZE VALUES BETWEEN 0 AND 1 INSTEAD OF 0 TO 255 return img X_trai...
img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) return img
identifier_body
proxyws.go
{ defer util.HandlePanic() atomic.AddUint64(&(pws.ConnCount), 1) var ( serverConn *websocket.Conn //tcpAddr *net.TCPAddr wsaddr = r.RemoteAddr ) //获取客户端的serverID 从http.head的Sec-Websocket-Protocol字段中获取,是与客户端商定的 whead := w.Header() serverID := r.Header.Get("Sec-Websocket-Protocol") if "" == serverID...
} nwrite = len(message) clientRecv += int64(nwrite) ConnMgr.UpdateClientInSize(int64(nwrite)) if err = serverConn.SetWriteDeadline(time.Now().Add(pws.SendBlockTime)); err != nil { log.Info("Session(%s -> %s, TLS: %v) Closed, Client SetWriteDeadline Err: %s", wsaddr, line.Remote, pws.EnableTls,...
wsaddr, line.Remote, pws.EnableTls, err.Error()) break } util.Go(s2c)
random_line_split
proxyws.go
} serverConn, _, err = dialer.Dial(addr, nil) if err != nil { log.Info("Session(%s -> %s, TLS: %v) DialTCP Err: %s", wsaddr, line.Remote, pws.EnableTls, err.Error()) wsConn.Close() //线路延迟 line.UpdateDelay(UnreachableTime) //统计连接失败数 line.UpdateFailedNum(1) ConnMgr.U...
, SendBufLen: DEFAULT_TCP_WRITE_BUF_LEN, linelay: DEFAULT_TCP_NODELAY, Certs: certs, Routes: map[string]func(w http.ResponseWriter, r *http.Request){}, RealIpMode: realIpModel, ProxyBase: &ProxyBase{ name: name, ptype: PT_WEBSOCKET, local: local, lines: []*Line{}, }...
identifier_body
proxyws.go
defer util.HandlePanic() atomic.AddUint64(&(pws.ConnCount), 1) var ( serverConn *websocket.Conn //tcpAddr *net.TCPAddr wsaddr = r.RemoteAddr ) //获取客户端的serverID 从http.head的Sec-Websocket-Protocol字段中获取,是与客户端商定的 whead := w.Header() serverID := r.Header.Get("Sec-Websocket-Protocol") if "" == serverID { ...
//统计负载量 line.UpdateLoad(1) defer line.UpdateLoad(-1) //统计当前连接数 ConnMgr.UpdateOutNum(1) defer ConnMgr.UpdateOutNum(-1) //统计连接成功数 ConnMgr.UpdateSuccessNum(1) log.Info("Session(%s -> %s, TLS: %v) Established", wsaddr, line.Remote, pws.EnableTls) //传真实IP if err = line.HandleR...
f pws.EnableTls { dialer.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} addr = "wss://" + line.Remote } serverConn, _, err = dialer.Dial(addr, nil) if err != nil { log.Info("Session(%s -> %s, TLS: %v) DialTCP Err: %s", wsaddr, line.Remote, pws.EnableTls, err.Error()) wsCo...
conditional_block
proxyws.go
ttp.ResponseWriter, r *http.Request) { defer util.HandlePanic() atomic.AddUint64(&(pws.ConnCount), 1) var ( serverConn *websocket.Conn //tcpAddr *net.TCPAddr wsaddr = r.RemoteAddr ) //获取客户端的serverID 从http.head的Sec-Websocket-Protocol字段中获取,是与客户端商定的 whead := w.Header() serverID := r.Header.Get("Sec-Web...
w(w h
identifier_name
MAIN PROGRAMME.py
, text='Enter ticker (e.g. "AAPL", "MSFT", "TSLA"):').grid(row=0, column=0, sticky=W) self.ticker = StringVar() Entry(self.root, width=6, textvariable=self.ticker).grid(row=0, column=1, sticky=W) Button(self.root, text='get info', command=self.get_info).grid(row=0, column=2, sticky=W) self.chart_type = 'yearly'...
(self): #, chart_type='yearly'): ''' gets the chart: currently: daily chart from bigcharts to do: specify which chart we want ''' ticker = str(self.ticker.get()).upper() urls = {'yearly': 'http://bigcharts.marketwatch.com/quickchart/quickchart.asp?symb=' + ticker + '&insttype=&freq=&show=', '1 Month': 'http:...
get_chart
identifier_name
MAIN PROGRAMME.py
) def update_chart(self): ''' takes a chart time and then refreshes the chart ''' curser = self.chart_time.curselection()[-1] types = {0: 'Intraday', 1: '5 Days', 2: '1 Month', 3: 'yearly'} self.chart_type = types[curser] self.get_chart() #yahoo: def int_to_millions(self, number): ''' takes an int an...
''' creates hyperlink for press releases ''' ticker = str(self.ticker.get()).upper() webbrowser.open_new(self.press[0][1])
identifier_body
MAIN PROGRAMME.py
, text='Enter ticker (e.g. "AAPL", "MSFT", "TSLA"):').grid(row=0, column=0, sticky=W) self.ticker = StringVar() Entry(self.root, width=6, textvariable=self.ticker).grid(row=0, column=1, sticky=W) Button(self.root, text='get info', command=self.get_info).grid(row=0, column=2, sticky=W) self.chart_type = 'yearly'...
else: n = ('{:.1f}K'.format(int(number)/1000)) except ValueError: n = 'N/A' return n def two_decimals(self, number): ''' takes a float and formats it to only two decimals ''' return ('{:.2f}'.format(float(number))) def display_yahoo(self): ''' opens the yahoo information, also closes the old ...
n = ('{:.1f}M'.format(int(number)/1000000))
conditional_block
MAIN PROGRAMME.py
, text='Enter ticker (e.g. "AAPL", "MSFT", "TSLA"):').grid(row=0, column=0, sticky=W) self.ticker = StringVar() Entry(self.root, width=6, textvariable=self.ticker).grid(row=0, column=1, sticky=W) Button(self.root, text='get info', command=self.get_info).grid(row=0, column=2, sticky=W) self.chart_type = 'yearly'...
self.label_2.grid(row=3, column=0, sticky = W) self.label_3 = Label(self.root, text=self.volume) self.label_3.grid(row=4, column=0, sticky = W) self.label_4 = Label(self.root, text=self.high_52) self.label_4.grid(row=5, column=0, sticky = W) self.label_6 = Label(self.root, text=self.low_52) self.label_6.g...
self.label_2 =Label(self.root, text=self.change)
random_line_split
types.go
.Ref) bool // MonitorProcess creates monitor between the processes. // Allowed types for the 'process' value: etf.Pid, gen.ProcessID // When a process monitor is triggered, a MessageDown sends to the caller. // Note: The monitor request is an asynchronous signal. That is, it takes // time before the signal reache...
IsMessageDown
identifier_name
types.go
a MessageDown sends to the caller. // Note: The monitor request is an asynchronous signal. That is, it takes // time before the signal reaches its destination. MonitorProcess(process interface{}) etf.Ref // DemonitorProcess removes monitor. Returns false if the given reference wasn't found DemonitorProcess(ref e...
{ var md MessageDown switch m := message.(type) { case MessageDown: return m, true } return md, false }
identifier_body
types.go
Send(to interface{}, message etf.Term) error // SendAfter starts a timer. When the timer expires, the message sends to the process // identified by 'to'. 'to' can be a Pid, registered local name or // gen.ProcessID{RegisteredName, NodeName}. Returns cancel function in order to discard // sending a message. Cance...
From etf.Pid Message interface{} } // ProcessDirectMessage type ProcessDirectMessage struct { Ref etf.Ref Message interface{} Err error } // ProcessGracefulExitRequest type ProcessGracefulExitRequest struct { From etf.Pid Reason string } // ProcessState type ProcessState struct { Process State ...
// ProcessMailboxMessage type ProcessMailboxMessage struct {
random_line_split
ai.py
', 'board score wc bc ep kp depth captured')): """ A state of a chess game board -- a 120 char representation of the board score -- the board evaluation wc -- the castling rights, [west/queen side, east/king side] bc -- the opponent castling rights, [west/king side, east/queen side] ep - the en ...
def rotate(self): # Rotates the board, preserving enpassant # Allows logic to be reused, as only one board configuration must be considered return Position( self.board[::-1].swapcase(), -self.score, self.bc, self.wc, 119 - self.ep if self.ep else 0, 119 ...
for j in count(i + d, d): # j - final position index # q - occupying piece code q = self.board[j] # Stay inside the board, and off friendly pieces if q.isspace() or q.isupper(): break # Pawn move, dou...
conditional_block
ai.py
wc[1]) if i == H1: wc = (wc[0], False) if j == A8: bc = (bc[0], False) if j == H8: bc = (False, bc[1]) # Castling Logic if p == 'K': wc = (False, False) if abs(j - i) == 2: kp = (i + j) // 2 board = put(board, A1 if j < i e...
max_play
identifier_name
ai.py
', 'board score wc bc ep kp depth captured')): """ A state of a chess game board -- a 120 char representation of the board score -- the board evaluation wc -- the castling rights, [west/queen side, east/king side] bc -- the opponent castling rights, [west/king side, east/queen side] ep - the en ...
file_names = ["a", "b", "c", "d", "e", "f", "g", "h"] return file_names[(square_index % 10) - 1] def square_rank(square_index): return 10 - (square_index // 10) def square_san(square_index): # convert square index (21 - 98) to Standard Algebraic Notation square = namedtuple('square', 'file rank'...
return A1 + file_index - (10 * rank_index) def square_file(square_index):
random_line_split
ai.py
the last move """ def gen_moves(self): for i, p in enumerate(self.board): # i - initial position index # p - piece code # if the piece doesn't belong to us, skip it if not p.isupper(): continue for d in directions[p]: # d - p...
""" This is called when the game ends, you can clean up your data and dump files here if need be. Args: won (bool): True means you won, False means you lost. reason (str): The human readable string explaining why you won or lost. """ pas...
identifier_body
helper.py
def create_dir(directory): """ create directory recursively """ try: os.makedirs(directory) logging.info('successfully created directory {}'.format(directory)) except OSError: logging.error('creating directory {} failed'.format(directory)) def check_path(path, isfi...
""" User response invoked when error exists """ valid_responses = ['y', 'NO'] response = '' while response not in valid_responses: logging.error('{}'.format(message)) response = input('Do you want to continue (y/NO): ') if response not in valid_responses: logging...
identifier_body
helper.py
valid_responses: logging.error('{}'.format(message)) response = input('Do you want to continue (y/NO): ') if response not in valid_responses: logging.info('Valid responses are \'y\' or \'NO\'') if response == 'NO': logging.info('QUITTING!!') sys.exit() def...
return ip def validate_file(directory, filename, url): re_hash = '' hash_value = False logging.info('validating file {} in {}'.format(filename, directory)) with open('{}/{}'.format(directory, filename), 'rb') as f: bytes = f.read() re_hash = hashlib.sha256(bytes).hexdigest() ...
ip = input('ip address for {} in {} node: '.format(ip_type, node_name)) ip_check = validate_ip(ip) if ip_check: break else: logging.warn('ip address should be in format: x.x.x.x')
conditional_block
helper.py
valid_responses: logging.error('{}'.format(message)) response = input('Do you want to continue (y/NO): ') if response not in valid_responses: logging.info('Valid responses are \'y\' or \'NO\'') if response == 'NO': logging.info('QUITTING!!') sys.exit() def...
logging.error('creating directory {} failed'.format(directory)) def check_path(path, isfile=False, isdir=False): """ returns if path given is a file or directory """ return os.path.isfile(path) if isfile else os.path.isdir(path) def set_values(user_input, default, check=''): """ ...
except OSError:
random_line_split
helper.py
valid_responses: logging.error('{}'.format(message)) response = input('Do you want to continue (y/NO): ') if response not in valid_responses: logging.info('Valid responses are \'y\' or \'NO\'') if response == 'NO': logging.info('QUITTING!!') sys.exit() def...
(selected_network_device, base_api_url, user, passwd): """ get mac address for a selected network device """ url = '{}/{}'.format(base_api_url, selected_network_device) device_mac_address = '' try: response = requests.get(url, verify=False, auth=(user, passwd), ...
get_mac_address
identifier_name
main.rs
16)? | 0xff000000)), _ => Err(anyhow!(ARGB_FORMAT_MSG)), } } } } use conf::{Argb, Config}; use font::Font; mod font { use anyhow::{Context, Result}; use rusttype::{self, point, Font as rtFont, Point, PositionedGlyph, Scale}; #[derive(Debug)] pub struct Font { ...
} else { self.cfg.nb }; } else { shm[(i, j)] = (self.cfg.nb & 0xffffff) | 0x22000000; } } } let scale = |v: u8, s: u8| ((v as u32 * s as u32) / 255) as u8; let (nf, sf...
{ if self.buffer.locked { return; } let shm = &mut self.buffer; let (bw, bh) = self.cfg.button_dim; let focus = { let cfg = &self.cfg; (self.ptr.btn) .filter(|s| s == &wl_pointer::ButtonState::Pressed) .and(self...
identifier_body
main.rs
16)? | 0xff000000)), _ => Err(anyhow!(ARGB_FORMAT_MSG)), } } } } use conf::{Argb, Config}; use font::Font; mod font { use anyhow::{Context, Result}; use rusttype::{self, point, Font as rtFont, Point, PositionedGlyph, Scale}; #[derive(Debug)] pub struct Font { ...
Surface { wl, layer, committed: false, configured: false, } } fn render(&mut self) { if self.buffer.locked { return; } let shm = &mut self.buffer; let (bw, bh) = self.cfg.button_dim; let focus ...
random_line_split
main.rs
(pub u32); static ARGB_FORMAT_MSG: &str = "Argb must be specified by a '#' followed by exactly 3, 4, 6, or 8 digits"; impl FromStr for Argb { type Err = anyhow::Error; fn from_str(s: &str) -> Result<Self> { if !s.starts_with('#') || !s[1..].chars().all(|c| c.is_ascii_hexdig...
Argb
identifier_name
lib.rs
ifier for #ident { const BITS: usize = #idx; type IntType = #size_type; type Interface = #size_type; fn to_interface(int_val: Self::IntType) -> Self::Interface { int_val as Self::Interface } } ) ...
} None }); let getters_setters = define_getters_setters(&s.fields); // Total size calculated as the sum of the inner `<T as Specifier>::BITS` associated consts let total_bit_size = quote!(0 #(+ <#fields_ty as Specifier>::BITS)...
{ // At this point `attr.tokens` is the following part of the attribute: // #[bits=..] // ^^^ let bits = syn::parse2::<BitAttribute>(attr.tokens.clone()).ok()?.bits; return S...
conditional_block
lib.rs
Specifier for #ident { const BITS: usize = #idx; type IntType = #size_type; type Interface = #size_type; fn to_interface(int_val: Self::IntType) -> Self::Interface { int_val as Self::Interface } } )...
// Check that fields with #[bits=X] attribute have a type of size `X` // We use an array size check to validate the size is correct let bits_attrs_check = s .fields .iter() .filter_map(|field| { let ty = &field.ty; ...
random_line_split
lib.rs
Specifier for #ident { const BITS: usize = #idx; type IntType = #size_type; type Interface = #size_type; fn to_interface(int_val: Self::IntType) -> Self::Interface { int_val as Self::Interface } } )...
() -> TokenStream { quote!( #[doc = "Simple trait to extract bits from primitive integer type"] trait BitOps { fn first(self, n: usize) -> u8; fn last(self, n: usize) -> u8; fn mid(self, start: usize, len: usize) -> u8; } #[doc = "Ops to extract b...
bit_ops_impl
identifier_name
lib.rs
Specifier for #ident { const BITS: usize = #idx; type IntType = #size_type; type Interface = #size_type; fn to_interface(int_val: Self::IntType) -> Self::Interface { int_val as Self::Interface } } )...
if attr.path.is_ident("bits") { // At this point `attr.tokens` is the following part of the attribute: // #[bits=..] // ^^^ let bits = syn::parse2::<BitAttribute>(attr.tokens.clo...
{ let _ = args; let item = parse_macro_input!(input as syn::Item); match item { Item::Struct(s) => { let ident = &s.ident; let fields_ty = s.fields.iter().map(|field| &field.ty); // Check that fields with #[bits=X] attribute have a type of size `X` /...
identifier_body
signalStream.js
typeof message.__internal_webrtc === 'undefined' || senderClientId === clientId) { return false; } // No reason to do this all now, so we use setImmdiate. setImmediate(handleSignal, payload.id, senderClientId, message); return true; }); function handleSignal(wid, senderClientId, message)
// Other clients may be responding to the same recipientId/stream. Therefore, the streamer // can't create a WebRTCClient with the original recipientId as these would override each // other in the webrtcClients map (the streamer would be creating two entries with the same // recipientId). Instead, the strea...
{ const node = coreUtils.getElementByWid(wid); if (message.requestForStreams) { Array.from(wantToStreamCallbacks.get(wid).keys()).forEach(ownId => { node.webstrate.signal({ __internal_webrtc: true, wantToStream: true, senderId: ownId, recipientId: message.senderId }, senderClientId); }); ...
identifier_body
signalStream.js
typeof message.__internal_webrtc === 'undefined' || senderClientId === clientId) { return false; } // No reason to do this all now, so we use setImmdiate. setImmediate(handleSignal, payload.id, senderClientId, message); return true; }); function
(wid, senderClientId, message) { const node = coreUtils.getElementByWid(wid); if (message.requestForStreams) { Array.from(wantToStreamCallbacks.get(wid).keys()).forEach(ownId => { node.webstrate.signal({ __internal_webrtc: true, wantToStream: true, senderId: ownId, recipientId: message.senderId ...
handleSignal
identifier_name
signalStream.js
typeof message.__internal_webrtc === 'undefined' || senderClientId === clientId) { return false; } // No reason to do this all now, so we use setImmdiate. setImmediate(handleSignal, payload.id, senderClientId, message); return true; }); function handleSignal(wid, senderClientId, message) { const node = coreUti...
const ownId = coreUtils.randomString(); wantToListenCallbacks.get(wid).set(ownId, callback); node.webstrate.signal({ __internal_webrtc: true, request
{ signaling.subscribe(wid); }
conditional_block
signalStream.js
typeof message.__internal_webrtc === 'undefined' || senderClientId === clientId) { return false; } // No reason to do this all now, so we use setImmdiate. setImmediate(handleSignal, payload.id, senderClientId, message); return true; }); function handleSignal(wid, senderClientId, message) { const node = coreUti...
if(event.candidate != null) { node.webstrate.signal({ ice: event.candidate, __internal_webrtc: true, senderId: ownId, recipientId }, clientRecipientId); } }; const gotStateChange = event => { switch (peerConnection.iceConnectionState) { case 'connected': onConnectCallback && onConn...
}; const gotIceCandidate = (event) => {
random_line_split
gfsworkflow.py
120', '126', '132', '138', '144', '150', '156', '162', '168'] # this is where the actual downloads happen. set the url, filepath, then download subregions = { 'hispaniola': 'subregion=&leftlon=-75&rightlon=-68&toplat=20.5&bottomlat=17', 'centralamerica': 'subregion=&leftlon=-94.25&rightlon=-75....
return False logging.info('Finished Downloads') return True def gfs_tiffs(threddspath, wrksppath, timestamp, region, model): """ Script to combine 6-hr accumulation grib files into 24-hr accumulation geotiffs. Dependencies: datetime, os, numpy, rasterio """ logging.info('\nSta...
logging.info('Probably a problem with the URL. Check the log and try the link')
conditional_block
gfsworkflow.py
fc_date = datetime.datetime.strptime(timestamp, "%Y%m%d%H").strftime("%Y%m%d") # This is the List of forecast timesteps for 5 days (6-hr increments). download them all fc_steps = ['006', '012', '018', '024', '030', '036', '042', '048', '054', '060', '066', '072', '078', '084', '090', '096',...
time = datetime.datetime.strptime(timestamp, "%Y%m%d%H").strftime("%H")
random_line_split
gfsworkflow.py
datetime, os, numpy, rasterio """ logging.info('\nStarting to process the ' + model + ' gribs into GeoTIFFs') # declare the environment tiffs = os.path.join(wrksppath, region, model + '_GeoTIFFs') gribs = os.path.join(threddspath, region, model, timestamp, 'gribs') netcdfs = os.path.join(thredd...
nc_georeference
identifier_name
gfsworkflow.py
logging.info('\ndone with zonal statistics, rounding values, writing to a csv file') stats_df = stats_df.round({'max': 1, 'mean': 1}) stats_df.to_csv(stat_file, index=False) # delete the resampled tiffs now that we dont need them logging.info('deleting the resampled tiffs directory') shutil.rmtree...
logging.info('\nGenerating a new color scale csv for the ' + model + ' results') colorscales = os.path.join(wrksppath, region, model + 'colorscales.csv') results = os.path.join(wrksppath, region, model + 'results.csv') logging.info(results) answers = pd.DataFrame(columns=['cat_id', 'cum_mean', 'mean', '...
identifier_body
frontend.rs
pub enum Authentication { Failed, InProgress, Authenticated(String), } struct AccessTokenParameter<'a> { valid: bool, client_id: Option<Cow<'a, str>>, redirect_url: Option<Cow<'a, str>>, grant_type: Option<Cow<'a, str>>, code: Option<Cow<'a, str>>, authorization: Option<(String, Vec...
#[derive(Clone)]
random_line_split
frontend.rs
<'a, str>>, authorization: Option<(String, Vec<u8>)>, } struct GuardParameter<'a> { valid: bool, token: Option<Cow<'a, str>>, } /// Abstraction of web requests with several different abstractions and constructors needed by this /// frontend. It is assumed to originate from an HTTP request, as defined in t...
} impl<'s> AuthorizationParameter<'s> { fn invalid() -> Self { AuthorizationParameter { valid: false, method: None, client_id: None, scope: None, redirect_url: None, state: None } } } impl AuthorizationFlow { /// Idempotent data processing, checks formats. pub fn prepare<W: WebReq...
{ self.method.as_ref().map(|c| c.as_ref().into()) }
identifier_body
frontend.rs
<'a, str>>, authorization: Option<(String, Vec<u8>)>, } struct GuardParameter<'a> { valid: bool, token: Option<Cow<'a, str>>, } /// Abstraction of web requests with several different abstractions and constructors needed by this /// frontend. It is assumed to originate from an HTTP request, as defined in t...
<'l, Req> where Req: WebRequest + 'l, { request: &'l mut Req, urldecoded: AuthorizationParameter<'l>, } fn extract_parameters(params: HashMap<String, Vec<String>>) -> AuthorizationParameter<'static> { let map = params.iter() .filter(|&(_, v)| v.len() == 1) .map(|(k, v)| (k.as_str(), v[0...
PreparedAuthorization
identifier_name
wx.py
[(block, [])]) ]) else: return ({'type': 'Anchor', 'point': point}, []) elif macro in layer_macros: return ({'type': 'Layer', 'level': macro.upper()}, children) elif macro == 'anchor': anchor = {'type': 'Anchor'} for key in ('point', 'relativePoint', 'rel...
construct
identifier_name
wx.py
not (3 <= len(args) <= 4): raise ValueError() block.update(type='Color', r=args[0], g=args[1], b=args[2]) if len(args) == 4: block['a'] = args[3] return (block, []) elif macro == 'hitrectinsets': if len(args) != 4: raise ValueError() retur...
xmlfile = path.join(target_dir, path.basename(source_file).replace('.wx', '.xml'))
random_line_split
wx.py
return ({'type': 'Anchor', 'point': point}, [ ({'type': 'Offset'}, [(block, [])]) ]) else: return ({'type': 'Anchor', 'point': point}, []) elif macro in layer_macros: return ({'type': 'Layer', 'level': macro.upper()}, children) elif macro == 'a...
lines[i] = indent + ' ' + lines[i]
conditional_block
wx.py
'LeftLabel': ['FontString', 'epLeftLabel'], 'ListBuilder': ['Frame', 'epListBuilder'], 'MessageFrame': ['Frame', 'epMessageFrame'], 'MessageFrameBase': ['Frame', 'epMessageFrameBase'], 'MultiButton': ['Button', 'epMultiButton'], 'MultiFrame': ['Frame', 'epMultiFrame'], 'Panel': ['Frame', 'ep...
candidates = flag | keyvalue | parent | parentkey | token | value arguments = ~Token('\(') & Extend(candidates[:, comma]) & ~Token('\)') > _parse_arguments declaration = token[1:] & arguments[0:1] assignment_line = Line(Token('%[A-Za-z]+') & ~Token('=') & value) > (lambda v: {v[0]: v[1]}) blank_line = ~Line(Empty(),...
offset = 1 if tokens[0][1] == ' ': offset = 2 return '\n'.join([token[offset:] for token in tokens])
identifier_body
writer.go
ups" ini:"maxbackups"` // Compress determines if the rotated log files should be compressed // using gzip. The default is not to perform compression. Compress bool `json:"compress" ini:"compress"` CustomerBackupFormat string rotateRunning bool size int64 file *os.File mu sync.Mut...
() error { l.mu.Lock() defer l.mu.Unlock() return l.close() } // rotate func (l *FileWriter) startRotateCron() { c := cron.New() c.AddFunc(l.RotateCron, func() { if l.rotateRunning { return } l.rotateRunning = true if err := l.Rotate(); err != nil { } l.rotateRunning = false }) c.Start() } // cl...
Close
identifier_name
writer.go
ups" ini:"maxbackups"` // Compress determines if the rotated log files should be compressed // using gzip. The default is not to perform compression. Compress bool `json:"compress" ini:"compress"` CustomerBackupFormat string rotateRunning bool size int64 file *os.File mu sync.Mut...
} if err != nil { return fmt.Errorf("error getting log file info: %s", err) } file, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, 0644) if err != nil { // if we fail to open the old log file for some reason, just ignore // it and open a new log file. return l.openNew() } l.file = file l.size = ...
filename := l.filename() info, err := os_Stat(filename) if os.IsNotExist(err) { return l.openNew()
random_line_split
writer.go
p.FileName = "./default.log" } if p.RotateCron == defaultLogName { p.RotateCron = defaultRotateCron } p.startRotateCron() } // Write implements io.Writer. If a write would cause the log file to be larger // than MaxSize, the file is closed, renamed to include a timestamp of the // current time, and a new log f...
{ return filepath.Dir(l.filename()) }
identifier_body
writer.go
" ini:"maxbackups"` // Compress determines if the rotated log files should be compressed // using gzip. The default is not to perform compression. Compress bool `json:"compress" ini:"compress"` CustomerBackupFormat string rotateRunning bool size int64 file *os.File mu sync.Mutex ...
l.rotateRunning = false }) c.Start() } // close closes the file if it is open. func (l *FileWriter) close() error { if l.file == nil { return nil } err := l.file.Close() l.file = nil return err } // Rotate causes FileWriter to close the existing log file and immediately create a // new one. This is a hel...
{ }
conditional_block
converter.go
atchdog(vmi.Spec.Domain.Devices.Watchdog, newWatchdog, c) // if err != nil { // return err // } // domain.Spec.Devices.Watchdog = newWatchdog // } // if vmi.Spec.Domain.Devices.Rng != nil { // newRng := &Rng{} // err := Convert_v1_Rng_To_api_Rng(vmi.Spec.Domain.Devices.Rng, newRng, c) // if err != nil...
{ if cfg.Value < 0 { return Memory{Unit: "B"}, fmt.Errorf("Memory size '%d' must be greater than or equal to 0", cfg.Value) } var memorySize uint64 switch cfg.Unit { case "gib": memorySize = cfg.Value * 1024 * 1024 * 1024 case "mib": memorySize = cfg.Value * 1024 * 1024 case "kib": memorySize = cfg.Valu...
identifier_body
converter.go
return err // } // } // } if taskCfg.CPU.Model == "" { domainSpec.CPU.Mode = CPUModeHostModel } // if vmi.Spec.Domain.Devices.AutoattachGraphicsDevice == nil || *vmi.Spec.Domain.Devices.AutoattachGraphicsDevice == true { // var heads uint = 1 // var vram uint = 16384 // domain.Spec.Devices.Video...
{ return &ReadOnly{} }
conditional_block
converter.go
) // if err != nil { // return err // } // domain.Spec.Devices.Watchdog = newWatchdog // } // if vmi.Spec.Domain.Devices.Rng != nil { // newRng := &Rng{} // err := Convert_v1_Rng_To_api_Rng(vmi.Spec.Domain.Devices.Rng, newRng, c) // if err != nil { // return err // } // domain.Spec.Devices.Rng ...
setDiskSpec
identifier_name
converter.go
ioThreadId := defaultIOThread // dedicatedThread := false // if disk.DedicatedIOThread != nil { // dedicatedThread = *disk.DedicatedIOThread // } // if dedicatedThread { // ioThreadId = currentDedicatedThread // currentDedicatedThread += 1 // } else { // ioThreadId = currentAutoThread...
random_line_split
router.rs
verifier router routes requests to either the checkpoint verifier or the /// semantic block verifier, depending on the maximum checkpoint height. /// /// # Correctness /// /// Block verification requests should be wrapped in a timeout, so that /// out-of-order and invalid requests do not hang indefinitely. See the [`r...
<S>( config: Config, network: Network, mut state_service: S, debug_skip_parameter_preload: bool, ) -> ( Buffer<BoxService<Request, block::Hash, RouterError>, Request>, Buffer< BoxService<transaction::Request, transaction::Response, TransactionError>, transaction::Request, >, ...
init
identifier_name
router.rs
, Error)] #[allow(missing_docs)] pub enum RouterError { /// Block could not be checkpointed Checkpoint { source: Box<VerifyCheckpointError> }, /// Block could not be full-verified Block { source: Box<VerifyBlockError> }, } impl From<VerifyCheckpointError> for RouterError { fn from(err: VerifyCheckp...
unreachable!("unexpected response type: {response:?} from state request") }
conditional_block
router.rs
verifier router routes requests to either the checkpoint verifier or the /// semantic block verifier, depending on the maximum checkpoint height. /// /// # Correctness /// /// Block verification requests should be wrapped in a timeout, so that /// out-of-order and invalid requests do not hang indefinitely. See the [`r...
// # Consensus // // We want to verify all available checkpoints, even if the node is not configured // to use them for syncing. Zebra's checkpoints are updated with every release, // which makes sure they include the latest settled network upgrade. ...
tracing::info!("starting state checkpoint validation");
random_line_split
javascript.rs
: &'a LineNumbers, module: &'a TypedModule, float_division_used: bool, object_equality_used: bool, module_scope: im::HashMap<String, usize>, } impl<'a> Generator<'a> { pub fn new(line_numbers: &'a LineNumbers, module: &'a TypedModule) -> Self { Self { line_numbers, m...
fn imported_external_function( &mut self, public: bool, name: &'a str, module: &'a str, fun: &'a str, ) -> Document<'a> { let import = if name == fun { docvec!["import { ", name, r#" } from ""#, module, r#"";"#] } else { docvec![ ...
{ if module.is_empty() { self.global_external_function(public, name, arguments, fun) } else { self.imported_external_function(public, name, module, fun) } }
identifier_body
javascript.rs
, float_division_used: false, object_equality_used: false, module_scope: Default::default(), } } pub fn compile(&mut self) -> Output<'a> { let statements = std::iter::once(Ok(r#""use strict";"#.to_doc())).chain( self.module .statem...
wrap_object
identifier_name
javascript.rs
_numbers: &'a LineNumbers, module: &'a TypedModule, float_division_used: bool, object_equality_used: bool, module_scope: im::HashMap<String, usize>, } impl<'a> Generator<'a> { pub fn new(line_numbers: &'a LineNumbers, module: &'a TypedModule) -> Self { Self { line_numbers, ...
"export function " } else { "function " }; Ok(docvec![ head, maybe_escape_identifier(name), fun_args(args), " {", docvec![line(), generator.function_body(body)?] .nest(INDENT) .gro...
&mut self.object_equality_used, self.module_scope.clone(), ); let head = if public {
random_line_split
benchmarks.rs
let mut state = state.clone(); play_out ( &mut Runner::new (&mut state, true, false), strategy, ); CombatResult::new (& state) } // Note: This meta strategy often performed WORSE than the naive strategy it's based on, // probably because it chose lucky moves rather than good moves ...
let mut fast_genetic: ExplorationOptimizer<FastStrategy, _> = ExplorationOptimizer::new (| candidates: & [CandidateStrategy <FastStrategy>] | { if candidates.len() < 2 { FastStrategy::random() } else { FastStrategy::offspring(& candidates.choose_multiple(&mut rand::thread_rng(), 2).map (| cand...
random_line_split
benchmarks.rs
<T> { strategy: T, playouts: usize, total_score: f64, } fn playout_result(state: & CombatState, strategy: & impl Strategy)->CombatResult { let mut state = state.clone(); play_out ( &mut Runner::new (&mut state, true, false), strategy, ); CombatResult::new (& state) } ...
CandidateStrategy
identifier_name
benchmarks.rs
mut state = state.clone(); play_out ( &mut Runner::new (&mut state, true, false), strategy, ); CombatResult::new (& state) } // Note: This meta strategy often performed WORSE than the naive strategy it's based on, // probably because it chose lucky moves rather than good moves stru...
let mut neural_random_only: ExplorationOptimizer<NeuralStrategy, _> = ExplorationOptimizer::new (|_: &[CandidateStrategy <NeuralStrategy>] | NeuralStrategy::new_random(&ghost_state, 16)); let mut neural_training_only = NeuralStrategy::new_random(&ghost_state, 16); let mut neural_random_training: ExplorationOpt...
stStrategy::offspring(& candidates.choose_multiple(&mut rand::thread_rng(), 2).map (| candidate | & candidate.strategy).collect::<Vec<_>>()) } });
conditional_block
benchmarks.rs
Runner::new (&mut state, true, false), strategy, ); CombatResult::new (& state) } // Note: This meta strategy often performed WORSE than the naive strategy it's based on, // probably because it chose lucky moves rather than good moves struct MetaStrategy <'a, T>(&'a T); impl <'a, T: Strategy> S...
timization_playouts = 1000000; let test_playouts = 10000; let ghost_file = std::fs::File::open ("data/hexaghost.json").unwrap(); let ghost_state: CombatState = serde_json::from_reader (std::io::BufReader::new (ghost_file)).unwrap(); let mut fast_random: ExplorationOptimizer<FastStrategy, _> = ExplorationOpti...
identifier_body
project-payment-record.ts
.href.split('#')[0]; // 当前网页的URL,不包含#及其后面部分 // let data = { url: url }; this.http.get(hideAttentionMenuUrl).subscribe(res => { if (res['code'] == 200) { wx.config({ debug: false, appId: res['data'].appid, timestamp: res['data'].timestamp, nonceStr: res['data...
ata; // let projectInvoiceDetailUrl = 'http://mam
conditional_block
project-payment-record.ts
Urlvalue: any public paymentRecordData = {} public payerList = {}; public isComplete = false; public data = {}; public isCompleteRecord = false public tipstext: any public isFailed: any constructor(public navCtrl: NavController, public navParams: NavParams, private transfer: FileTransfer, private file: ...
value) { this.paymentRecordData['payer'] = value.name; this.paymentRecordData['payerBank'] = value.bankName; this.paymentRecordData['payerAccount'] = value.account; } else { this.paymentRecordData[field] = value; } } getUrlParam(name) { var reg = new RegExp("(^|&)" + name + "=(...
ntRecordData, type: 'clientType', cid: cid }); } else { this.navCtrl.push(FormEditPage, { callback: this.setValue, value: value, field: field, type: type }); } } /*设置值(回调函数)*/ // setValue = (field,value)=> { // this.paymentRecordData[field] = value; // } /*设置值(回调函数)*/ setValue = (field,...
identifier_body
project-payment-record.ts
Urlvalue: any public paymentRecordData = {} public payerList = {}; public isComplete = false; public data = {}; public isCompleteRecord = false public tipstext: any public isFailed: any constructor(public navCtrl: NavController, public navParams: NavParams, private transfer: FileTransfer, private file: ...
bj.fileSize / 1048576; this.filesize = (obj.fileSize / 1048576).toPrecision(3); this.fileurl = obj.url; this.paymentRecordData['sourceName'] = this.filetitle this.paymentRecordData['size'] = this.filesize this.paymentRecordData['certifiedUrl'] = this.fileurl this.paymentRecordData['fid'] = obj.f...
// var a = o
identifier_name
project-payment-record.ts
fileUrlvalue: any public paymentRecordData = {} public payerList = {}; public isComplete = false; public data = {}; public isCompleteRecord = false public tipstext: any public isFailed: any constructor(public navCtrl: NavController, public navParams: NavParams, private transfer: FileTransfer, private f...
// let data = { url: url }; this.http.get(hideAttentionMenuUrl).subscribe(res => { if (res['code'] == 200) { wx.config({ debug: false, appId: res['data'].appid, timestamp: res['data'].timestamp, nonceStr: res['data'].nonceStr, signature: res['data'...
//隐藏底部分享菜单 isAttention() { // let url = location.href.split('#')[0]; // 当前网页的URL,不包含#及其后面部分
random_line_split
odor-finder.py
ile_l,77) maxattr,_=torch.max(attr,dim=1) minattr,_=torch.min(attr,dim=1) relevance=maxattr+minattr relevance=relevance.cpu().detach().numpy() data_relevance=pd.DataFrame() data_relevance["values"]=relevance len_smile=min(len(x_input_smile), smile_l) # cropped_smile_relevance=data_relev...
_topk.loc[0]=['Empty','Empty']
conditional_block
odor-finder.py
TRAIN_DATA_FILE= getConfig("Task","train_data_file") apply_data_file= getConfig("Task","apply_data_file") result_file= getConfig("Task","result_file") smile_l=int(getConfig("Task","smile_length","75")) seq_l=int(getConfig("Task","sequence_length","315")) filename=getConfig("Task","filename") model_filename = getConfi...
try: return config[section][attribute] except: return default
identifier_body
odor-finder.py
) # self.fc_combined = nn.Sequential(nn.Linear(1000,100),nn.ReLU(),nn.Linear(100,100),nn.ReLU(),nn.Linear(100,100),nn.ReLU(),nn.Linear(100,100),nn.ReLU(),nn.Linear(100,10),nn.ReLU(),nn.Linear(10,output_dim)) # self.fc_combined = nn.Sequential(nn.Linear(smile_o+seq_o,100),nn.ReLU(),nn.BatchNorm1d(100, af...
eq): key="ABCDEFGHIJKLMNOPQRSTUVWXYZ^" seq=seq.upper() test_list=list(key) res = {val : idx for idx, val in enumerate(test_list)} threshold=seq_l if len(seq)<=threshold: seq=seq+("^"*(threshold-len(seq))) else: seq=seq[0:threshold] array=[[0 for j in range(len(key))] fo...
e_hot_seq(s
identifier_name
odor-finder.py
00),nn.ReLU(),nn.Linear(100,10),nn.ReLU(),nn.Linear(10,output_dim)) # self.fc_combined = nn.Sequential(nn.Linear(smile_o+seq_o,100),nn.ReLU(),nn.BatchNorm1d(100, affine = False),nn.Dropout(.5),nn.Linear(100,10),nn.ReLU(),nn.Linear(10,output_dim)) # self.fc_combined = nn.Sequential(nn.Linear(smile_o+seq_...
if c.upper() not in "CBONSPFIK": print(mol[i], 0.0, "0xFFFFFF") else: if i + 1 < len(mol): n = mol[i+1]
random_line_split
record_trace.go
Name: "snapshotter", Usage: "snapshotter name.", Value: "overlaybd", }, cli.StringFlag{ Name: "runtime", Usage: "runtime name", Value: defaults.DefaultRuntime, }, cli.IntFlag{ Name: "max-concurrent-downloads", Usage: "Set the max concurrent downloads for each pull", Value: 8, }, ...
if err != nil { fmt.Printf("Failed to get task status: %v\n", err) } if st.Status == containerd.Running { if err = task
{ // Allow termination by user signals sigStop := make(chan bool) sigChan := registerSignals(ctx, task, sigStop) select { case <-sigStop: timer.Stop() break case <-watchStop: break case <-timer.C: fmt.Println("Timeout, stop recording ...") break } signal.Stop(sigChan) close(sigChan) st, err := t...
identifier_body
record_trace.go
Name: "snapshotter", Usage: "snapshotter name.", Value: "overlaybd", }, cli.StringFlag{ Name: "runtime", Usage: "runtime name", Value: defaults.DefaultRuntime, }, cli.IntFlag{ Name: "max-concurrent-downloads", Usage: "Set the max concurrent downloads for each pull", Value: 8, }, ...
// Create container and run task container, err := createContainer(ctx, client, cliCtx, image, traceFile) if err != nil { return err } defer container.Delete(ctx, containerd.WithSnapshotCleanup) task, err := tasks.NewTask(ctx, client, container, "", con, false, "", nil) if err != nil { return err ...
random_line_split
record_trace.go
"cni-plugin-dir", Usage: "cni plugin dir", Value: "/opt/cni/bin/", }, }, Action: func(cliCtx *cli.Context) (err error) { // Create client client, ctx, cancel, err := commands.NewClient(cliCtx) if err != nil { return err } defer cancel() cs := client.ContentStore() var con console.Console ...
createImageWithAccelLayer
identifier_name
record_trace.go
Name: "snapshotter", Usage: "snapshotter name.", Value: "overlaybd", }, cli.StringFlag{ Name: "runtime", Usage: "runtime name", Value: defaults.DefaultRuntime, }, cli.IntFlag{ Name: "max-concurrent-downloads", Usage: "Set the max concurrent downloads for each pull", Value: 8, }, ...
}() cniObj, err := createIsolatedNetwork(cliCtx) if err != nil { return err } defer func() { if nextErr := cniObj.Remove(ctx, networkNamespace, namespacePath); err == nil && nextErr != nil { err = errors.Wrapf(nextErr, "failed to teardown network") } }() if _, err = cniObj.Setup(c...
{ err = errors.Wrapf(err, "failed to delete netns") }
conditional_block
parser.js
5', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013']; function fetchRunnersFromPage(error, callback, url, start, year) { var options = { 'url': url, 'form': { 'start':start, 'next':'Next 25 Records' }, 'headers': { 'User-Agent':"Rested/2009 CFNetwork/673.2.1 Darwin/13.1.0 (x86_64) (Mac...
function doNext() { if (currentYearIndex >= years.length) { console.log("Done"); callback(runners); return;
{ currentYearIndex += 1; }
identifier_body
parser.js
05', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013']; function fetchRunnersFromPage(error, callback, url, start, year) { var options = { 'url': url, 'form': { 'start':start, 'next':'Next 25 Records' }, 'headers': { 'User-Agent':"Rested/2009 CFNetwork/673.2.1 Darwin/13.1.0 (x86_64) (Ma...
} } }); callback(runners); } } ); } ); } function runYear(error, callback, year) { var url = "http://registration.baa.org/cfm_Archive/iframe_ArchiveSearch.cfm?mode=results&criteria=&StoredProcParamsOn=yes&VarAgeLowID=0&VarAgeHighID=0&VarGenderID=0&VarBibNumber=&VarLastName=...
} else { var runner = parseRunnerBody($, row, lastRunnerWithHeader); if (runner) { runner.year = year; runners.push(runner);
random_line_split
parser.js
FirstName=&VarStateID=0&VarCountryOfResidenceID=0&VarCity=&VarZip=&VarTimeLowHr=&VarTimeLowMin=&VarTimeLowSec=00&VarTimeHighHr=&VarTimeHighMin=&VarTimeHighSec=59&VarSortOrder=ByName&VarAddInactiveYears=0&records=25&headerexists=Yes&bordersize=0&bordercolor=%23ffffff&rowcolorone=%23FFCC33&rowcolortwo=%23FFCC33&headercol...
stitchAllYearsTogether
identifier_name