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
distributed_dqn_v2.py
qn_model import _DQNModel from memory import ReplayBuffer from memory_remote import ReplayBuffer_remote import matplotlib.pyplot as plt from custom_cartpole import CartPoleEnv FloatTensor = torch.FloatTensor # =================== Helper Function =================== def plot_result(total_rewards ,learning_num, legen...
(self): return self.eval_model, self.steps def learn(self): self.steps += 1 if self.steps % self.update_steps == 0: self.update_batch() if self.steps % self.model_replace_freq == 0 and self.use_target_model: self.target_model.replace(self.eval_model) # ===...
getReturn
identifier_name
distributed_dqn_v2.py
qn_model import _DQNModel from memory import ReplayBuffer from memory_remote import ReplayBuffer_remote import matplotlib.pyplot as plt from custom_cartpole import CartPoleEnv FloatTensor = torch.FloatTensor # =================== Helper Function =================== def plot_result(total_rewards ,learning_num, legen...
def greedy_policy(self, state): return self.eval_model.predict(state) # =================== Ray Servers =================== @ray.remote class DQNModel_server(DQN_agent): def __init__(self, env, hyper_params, memory): super().__init__(env, hyper_params) self.memory_server = memory ...
else: #return action return self.greedy_policy(state)
random_line_split
distributed_dqn_v2.py
qn_model import _DQNModel from memory import ReplayBuffer from memory_remote import ReplayBuffer_remote import matplotlib.pyplot as plt from custom_cartpole import CartPoleEnv FloatTensor = torch.FloatTensor # =================== Helper Function =================== def plot_result(total_rewards ,learning_num, legen...
@ray.remote def evaluation_worker(model, env, max_episode_steps, tasks_num): total_reward = 0 for _ in range(tasks_num): state = env.reset() done = False steps = 0 while steps < max_episode_steps and not done: steps += 1 action = ray.get(model.greedy_po...
state = env.reset() done = False steps = 0 eval_model, total_steps = ray.get(model.getReturn.remote()) while steps < max_episode_steps and not done: steps += 1 a = ray.get(model.explore_or_exploit_policy.remote(state)) s_, reward, done, info = env.ste...
conditional_block
wasm_vm.rs
Store, Value, WasmerEnv, }; use wasmer_wasi::{Pipe, WasiEnv, WasiState}; use zellij_tile::data::{Event, EventType, PluginIds}; use crate::{ panes::PaneId, pty::PtyInstruction, screen::ScreenInstruction, thread_bus::{Bus, ThreadSenders}, }; use zellij_utils::errors::{ContextType, PluginContext}; #...
PluginInstruction::Render(buf_tx, pid, rows, cols) => { let (instance, plugin_env) = plugin_map.get(&pid).unwrap(); let render = instance.exports.get_function("render").unwrap(); render .call(&[Value::I32(rows as i32), Value::I32(cols as...
{ for (&i, (instance, plugin_env)) in &plugin_map { let subs = plugin_env.subscriptions.lock().unwrap(); // FIXME: This is very janky... Maybe I should write my own macro for Event -> EventType? let event_type = EventType::from_str(&event.to_st...
conditional_block
wasm_vm.rs
Store, Value, WasmerEnv, }; use wasmer_wasi::{Pipe, WasiEnv, WasiState}; use zellij_tile::data::{Event, EventType, PluginIds}; use crate::{ panes::PaneId, pty::PtyInstruction, screen::ScreenInstruction, thread_bus::{Bus, ThreadSenders}, }; use zellij_utils::errors::{ContextType, PluginContext}; #...
{ Load(Sender<u32>, PathBuf), Update(Option<u32>, Event), // Focused plugin / broadcast, event data Render(Sender<String>, u32, usize, usize), // String buffer, plugin id, rows, cols Unload(u32), Exit, } impl From<&PluginInstruction> for PluginContext { fn from(plugin_instruction: &PluginInstr...
PluginInstruction
identifier_name
wasm_vm.rs
Store, Value, WasmerEnv, }; use wasmer_wasi::{Pipe, WasiEnv, WasiState}; use zellij_tile::data::{Event, EventType, PluginIds}; use crate::{ panes::PaneId, pty::PtyInstruction, screen::ScreenInstruction, thread_bus::{Bus, ThreadSenders}, }; use zellij_utils::errors::{ContextType, PluginContext}; #...
fn host_open_file(plugin_env: &PluginEnv) { let path: PathBuf = wasi_read_object(&plugin_env.wasi_env); plugin_env .senders .send_to_pty(PtyInstruction::SpawnTerminal(Some(path))) .unwrap(); } fn host_set_timeout(plugin_env: &PluginEnv, secs: f64) { // There is a fancy, high-perfo...
{ let ids = PluginIds { plugin_id: plugin_env.plugin_id, zellij_pid: process::id(), }; wasi_write_object(&plugin_env.wasi_env, &ids); }
identifier_body
wasm_vm.rs
Store, Value, WasmerEnv, }; use wasmer_wasi::{Pipe, WasiEnv, WasiState}; use zellij_tile::data::{Event, EventType, PluginIds}; use crate::{ panes::PaneId, pty::PtyInstruction, screen::ScreenInstruction, thread_bus::{Bus, ThreadSenders}, }; use zellij_utils::errors::{ContextType, PluginContext}; #...
} PluginInstruction::Unload(pid) => drop(plugin_map.remove(&pid)), PluginInstruction::Exit => break, } } } // Plugin API --------------------------------------------------------------------------------------------------------- pub(crate) fn zellij_exports(store: &Store,...
buf_tx.send(wasi_read_string(&plugin_env.wasi_env)).unwrap();
random_line_split
state.rs
pub entropy: String, /// current battle count in this arena pub battle_cnt: u64, /// battle count from previous arenas pub previous_battles: u64, /// viewing key used with the card contracts pub viewing_key: String, /// contract info of all the card versions pub card_versions: Vec<St...
(self, versions: &[ContractInfo]) -> StdResult<Hero> { let hero = Hero { name: self.name, token_info: TokenInfo { token_id: self.token_info.token_id, address: versions[self.token_info.version as usize].address.clone(), }, pre_battle...
into_humanized
identifier_name
state.rs
pub address: CanonicalAddr, } /// tournament data #[derive(Serialize, Deserialize, Clone, Debug)] pub struct Tourney { /// tournament start time pub start: u64, /// tournament leaderboard pub leaderboard: Vec<Rank>, } /// leaderboards #[derive(Serialize, Deserialize, Clone, Debug)] pub struct Lea...
/// Returns StdResult<Vec<Battle>> of the battles to display /// /// # Arguments ///
random_line_split
state.rs
pub entropy: String, /// current battle count in this arena pub battle_cnt: u64, /// battle count from previous arenas pub previous_battles: u64, /// viewing key used with the card contracts pub viewing_key: String, /// contract info of all the card versions pub card_versions: Vec<St...
} /// code hash and address of a contract #[derive(Serialize, Deserialize, Clone, Debug)] pub struct StoreContractInfo { /// contract's code hash string pub code_hash: String, /// contract's address pub address: CanonicalAddr, } impl StoreContractInfo { /// Returns StdResult<ContractInfo> from co...
{ let battle = BattleDump { battle_number: self.battle_number, timestamp: self.timestamp, heroes: self .heroes .drain(..) .map(|h| h.into_dump(api, versions)) .collect::<StdResult<Vec<HeroDump>>>()?, ...
identifier_body
state.rs
wins: u32, /// number of ties pub ties: u32, /// number of times took 3rd place in a 2-way tie pub third_in_two_way_ties: u32, /// number of losses pub losses: u32, } impl Default for StorePlayerStats { fn default() -> Self { Self { score: 0, battles: 0, ...
{ result? }
conditional_block
testingfrog.rs
(|d| fs::read_to_string(d.path())) // .map_err(|e| Box::new(e) as Box<dyn Error>) // .as_ref().map(|x| Post::from_str(x).unwrap()) // .map_err(|e| todo!()) // }) // .collect::<BoxResult<Vec<_>>>()?; let blah = vec![fs::read_to_string( "./blog/...
// // impl<T> Debounced<T> { // fn recv(&self) -> Result<T, mpsc::RecvError> { // let mut prev = None; //
random_line_split
testingfrog.rs
raw_content: &'input str, } fn post_title(input: &str) -> IResult<&str, &str> { delimited(tag("title"), take_until("\n"), newline)(input) } fn post_tags(input: &str) -> IResult<&str, Vec<&str>> { delimited( pair(tag("tags:"), space0), separated_list0( tuple((space0, tag(","), spac...
fn post_header(input: &str) -> IResult<&str, (&str, Vec<&str>, PostStatus)> { delimited( pair(tag("---"), newline), tuple((post_title, post_tags, post_status)), pair(tag("---"), newline), )(input) } impl<'a> Post<'a> { fn from_str(input: &'a str) -> Result<Post<'a>, Box<dyn Error>...
{ delimited( tag("status:"), delimited( space1, alt(( map(tag("published"), |_| PostStatus::Published), map(tag("draft"), |_| PostStatus::Draft), )), space0, ), newline, )(input) }
identifier_body
testingfrog.rs
raw_content: &'input str, } fn post_title(input: &str) -> IResult<&str, &str> { delimited(tag("title"), take_until("\n"), newline)(input) } fn post_tags(input: &str) -> IResult<&str, Vec<&str>> { delimited( pair(tag("tags:"), space0), separated_list0( tuple((space0, tag(","), s...
(input: &str) -> IResult<&str, PostStatus> { delimited( tag("status:"), delimited( space1, alt(( map(tag("published"), |_| PostStatus::Published), map(tag("draft"), |_| PostStatus::Draft), )), space0, ), ...
post_status
identifier_name
sync.rs
userfile"; /// Abort the operation if the server doesn't respond for this time interval. const TIMEOUT_SECS: u64 = 10; /// The UPM sync protocol returns an HTTP body of "OK" if the request was successful, otherwise it /// returns one of these error codes: FILE_DOESNT_EXIST, FILE_WASNT_DELETED, FILE_ALREADY_EXISTS, ///...
self.check_response(&mut response)?; Ok(()) } /// Upload the provided database to the remote repository. The database is provided in raw /// form as a byte buffer. fn upload(&mut self, database_name: &str, database_bytes: Vec<u8>) -> Result<(), UpmError> { let url: String = sel...
// Process response
random_line_split
sync.rs
file"; /// Abort the operation if the server doesn't respond for this time interval. const TIMEOUT_SECS: u64 = 10; /// The UPM sync protocol returns an HTTP body of "OK" if the request was successful, otherwise it /// returns one of these error codes: FILE_DOESNT_EXIST, FILE_WASNT_DELETED, FILE_ALREADY_EXISTS, /// FIL...
(&self, response: &mut reqwest::Response) -> Result<(), UpmError> { if !response.status().is_success() { return Err(UpmError::Sync(format!("{}", response.status()))); } let mut response_code = String::new(); response.read_to_string(&mut response_code)?; if response_co...
check_response
identifier_name
sync.rs
file"; /// Abort the operation if the server doesn't respond for this time interval. const TIMEOUT_SECS: u64 = 10; /// The UPM sync protocol returns an HTTP body of "OK" if the request was successful, otherwise it /// returns one of these error codes: FILE_DOESNT_EXIST, FILE_WASNT_DELETED, FILE_ALREADY_EXISTS, /// FIL...
let local_password = match database.password() { Some(p) => p, None => return Err(UpmError::NoDatabasePassword), }; let remote_password = match remote_password { Some(p) => p, None => local_password, }; // 1. Download the remote database. // If the remote databa...
{ // Collect all the facts. if database.sync_url.is_empty() { return Err(UpmError::NoSyncURL); } if database.sync_credentials.is_empty() { return Err(UpmError::NoSyncCredentials); } let sync_account = match database.account(&database.sync_credentials) { Some(a) => a, ...
identifier_body
de.py
_latent() batch_indices = batch_indices.ravel() print(' ### ### ### computed full posterior') print(' ### ### ### url = ', url) # read submission csv and fetch selected cells submission = pd.read_csv(io.StringIO(requests.get(url).content.decode('utf-8')), index_col=0) selected_cells_csv_str...
filename = filename.replace('.csv', '')
random_line_split
de.py
Dataset() # we provide the `batch_indices` so that scvi can perform batch correction gene_dataset.populate_from_data( adata.X, gene_names=adata.var.index.values, cell_types=adata.obs['cell_type'].values, batch_indices=adata.obs['experiment'].cat.codes.values, ) vae = VA...
cell_idx2 = adata.obs['cell_type'] == '000000' for _, entry in submission[['cell_type2', 'experiment2']].dropna().iterrows(): cell = entry['cell_type2'].strip() experiment = entry['experiment2'].strip() curr_boolean = (adata.obs['cell_type'] == cell) & (adata.obs['experiment'] == expe...
cell = entry['cell_type1'].strip() experiment = entry['experiment1'].strip() curr_boolean = (adata.obs['cell_type'] == cell) & (adata.obs['experiment'] == experiment) cell_idx1 = (cell_idx1 | curr_boolean)
conditional_block
SceneL5.js
false; function Scene(canvasID, sceneURL) { // Set up WebGL context var t = this; this.canvasID = canvasID; var canvas = this.canvas = document.getElementById(canvasID); if (!canvas) { alert("Canvas ID '" + canvasID + "' not found."); return; } var gl = this.gl = WebGLUtils.setupWebGL(this.ca...
gl.clearColor(bgColor[0], bgColor[1], bgColor[2], bgColor[3]); // Set up User Interface elements this.fovSliderID = canvasID + "-fov-slider"; this.fovSlider = document.getElementById(this.fovSliderID); this.nearSliderID = canvasID + "-near-slider"; this.nearSlider = document.getElementById(this.nearS...
{ bgColor = jScene["bgColor"]; }
conditional_block
SceneL5.js
false; function
(canvasID, sceneURL) { // Set up WebGL context var t = this; this.canvasID = canvasID; var canvas = this.canvas = document.getElementById(canvasID); if (!canvas) { alert("Canvas ID '" + canvasID + "' not found."); return; } var gl = this.gl = WebGLUtils.setupWebGL(this.canvas); if (!gl) { ...
Scene
identifier_name
SceneL5.js
false; function Scene(canvasID, sceneURL)
// Load the scene definition var jScene = this.jScene = LoadJSON(sceneURL); if (jScene === null) return; // scene load failed (LoadJSON alerts on error) // Set up WebGL rendering settings gl.viewport(0, 0, canvas.width, canvas.height); gl.enable(gl.DEPTH_TEST); var bgColor = [ 0, 0, 0, 1 ]; if ("bgCol...
{ // Set up WebGL context var t = this; this.canvasID = canvasID; var canvas = this.canvas = document.getElementById(canvasID); if (!canvas) { alert("Canvas ID '" + canvasID + "' not found."); return; } var gl = this.gl = WebGLUtils.setupWebGL(this.canvas); if (!gl) { alert("WebGL isn'...
identifier_body
SceneL5.js
false; function Scene(canvasID, sceneURL) { // Set up WebGL context var t = this; this.canvasID = canvasID; var canvas = this.canvas = document.getElementById(canvasID); if (!canvas) { alert("Canvas ID '" + canvasID + "' not found."); return; } var gl = this.gl = WebGLUtils.setupWebGL(this.ca...
projection = perspective(camera.FOVdeg, aspect, camera.near, camera.far); } else { projection = ortho(-aspect, aspect, -1.0, 1.0, camera.near, camera.far); } // Build view transform and initialize matrix stack var matrixStack = new MatrixStack; ...
camera.perspective = this.perspectiveCheckBox.checked; if (camera.perspective) {
random_line_split
main.go
Key() string } /* * worker */ // TODO: change this into an error channel func reportError(d string, errmsg string, err error) { status.ErrorCount.Mark(1) log.Debugf("%s when processing %s: %s", errmsg, d, err) } func reportBundleDetails(routingKey string, body []byte, headers amqp.Table) { log.Errorf("Error wh...
reportBundleDetails(routingKey, body, headers) reportError(routingKey, "Could not process body", err) return } else if msg != nil { msgs = make([]map[string]interface{}, 0, 1) msgs = append(msgs, msg) } } } else if contentType == "application/json" { // Note for simplicity in implementati...
//log.Infof("Process Protobuf bundle returned %d messages and error = %v",len(msgs),err) } else { msg, err := ProcessProtobufMessage(routingKey, body, headers) if err != nil {
random_line_split
main.go
Key() string } /* * worker */ // TODO: change this into an error channel func reportError(d string, errmsg string, err error) { status.ErrorCount.Mark(1) log.Debugf("%s when processing %s: %s", errmsg, d, err) } func reportBundleDetails(routingKey string, body []byte, headers amqp.Table) { log.Errorf("Error wh...
} func processMessage(body []byte, routingKey, contentType string, headers amqp.Table, exchangeName string) { status.InputEventCount.Mark(1) status.InputByteCount.Mark(int64(len(body))) var err error var msgs []map[string]interface{} // // Process message based on ContentType // //log.Errorf("PROCESS MESSAGE...
{ status.InputChannelCount.Update(int64(len(inputChannel))) status.OutputChannelCount.Update(int64(len(outputChannel))) }
conditional_block
main.go
Key() string } /* * worker */ // TODO: change this into an error channel func reportError(d string, errmsg string, err error) { status.ErrorCount.Mark(1) log.Debugf("%s when processing %s: %s", errmsg, d, err) } func reportBundleDetails(routingKey string, body []byte, headers amqp.Table) { log.Errorf("Error wh...
status.LastConnectError = err.Error() status.ErrorTime = time.Now() return err } status.LastConnectTime = time.Now() status.IsConnected = true numProcessors := config.NumProcessors log.Infof("Starting %d message processors\n", numProcessors) wg.Add(numProcessors) if config.RunMetrics { go monitorChan...
{ var dialer AMQPDialer if config.CannedInput { md := NewMockAMQPDialer() mockChan, _ := md.Connection.Channel() go RunCannedData(mockChan) dialer = md } else { dialer = StreadwayAMQPDialer{} } var c *Consumer = NewConsumer(uri, queueName, consumerTag, config.UseRawSensorExchange, config.EventTypes, d...
identifier_body
main.go
Key() string } /* * worker */ // TODO: change this into an error channel func reportError(d string, errmsg string, err error) { status.ErrorCount.Mark(1) log.Debugf("%s when processing %s: %s", errmsg, d, err) } func reportBundleDetails(routingKey string, body []byte, headers amqp.Table) { log.Errorf("Error wh...
(deliveries <-chan amqp.Delivery) { defer wg.Done() for delivery := range deliveries { processMessage(delivery.Body, delivery.RoutingKey, delivery.ContentType, delivery.Headers, delivery.Exchange) } log.Info("Worker exiting") } func logFileProcessingLoop() <-chan error { errChan := make(chan erro...
worker
identifier_name
index.py
> mu_password: <password> md_username:<account name> md_password: <password> ''' from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.common.keys import Keys import time import yaml # constants # delays MANGA_UPDATES_DELAY = 0 # seconds for manga updates to load, usually can be set to...
def manga_updates_all_titles(driver, url=mu_url): ''' get a list of titles and returns a dict of manga_updates_url: set(all titles) ''' all_titles = {} href_list, title_list = manga_updates_list(driver, url) # initially fill with known values for i in range(len(title_list)): new...
''' gets reading list and returns dict of url: (volume number, chapter number) ''' reading_progress = dict() for url in reading_list.keys(): driver.get(url) time.sleep(MANGA_UPDATES_DELAY) soup = BeautifulSoup(driver.page_source, 'html.parser') volume, chapter = soup.fi...
identifier_body
index.py
> mu_password: <password> md_username:<account name> md_password: <password> ''' from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.common.keys import Keys import time import yaml # constants # delays MANGA_UPDATES_DELAY = 0 # seconds for manga updates to load, usually can be set to...
return reading_progress def manga_updates_all_titles(driver, url=mu_url): ''' get a list of titles and returns a dict of manga_updates_url: set(all titles) ''' all_titles = {} href_list, title_list = manga_updates_list(driver, url) # initially fill with known values for i in range(...
driver.get(url) time.sleep(MANGA_UPDATES_DELAY) soup = BeautifulSoup(driver.page_source, 'html.parser') volume, chapter = soup.find("td", {"id": "showList"}).find_all("b") volume = "".join([x for x in list(list(volume)[0]) if x.isdigit()]) chapter = "".join([x for x in list(list(...
conditional_block
index.py
> mu_password: <password> md_username:<account name> md_password: <password> ''' from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.common.keys import Keys import time import yaml # constants # delays MANGA_UPDATES_DELAY = 0 # seconds for manga updates to load, usually can be set to...
mu_url_on_hold_list = 'https://www.mangaupdates.com/mylist.html?list=hold' md_base_url = 'https://mangadex.org' md_login_url = 'https://mangadex.org/login' md_search_url = 'https://mangadex.org/quick_search/' def manga_updates_list(driver, url=mu_url): ''' gets list's unique urls and titles ''' driver...
mu_url_wish_list = 'https://www.mangaupdates.com/mylist.html?list=wish' mu_url_complete_list = 'https://www.mangaupdates.com/mylist.html?list=complete' mu_url_unfinished_list = 'https://www.mangaupdates.com/mylist.html?list=unfinished'
random_line_split
index.py
> mu_password: <password> md_username:<account name> md_password: <password> ''' from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.common.keys import Keys import time import yaml # constants # delays MANGA_UPDATES_DELAY = 0 # seconds for manga updates to load, usually can be set to...
(all_titles, driver, progress): ''' imports chapter and volume information for items in reading list ''' for key, titles in all_titles.items(): for title_name in titles: if not is_english(title_name): continue query = title_name.replace(" ", "%20") ...
mangadex_import_progress
identifier_name
inter.go
+= "\n" } cl = ed.line + ed.skip } content += ed.Format() } content += strings.Join(contentLines[cl:], "\n") return content } func (rs *Remarks) Severity() int { return rs.severity } func (rs *Remarks) Histo(severity int) int { if severity >= 0 && severity <= MAX { return rs.histo[severity] } retu...
sing(ht HeaderTransfer, lookup map[string]object) []string { friendly := make([]string, 0) ht.collectFriendly(&friendly) missing := make([]string, 0) for _, f := range friendly { if _, present := lookup[f]; !present { missing = append(missing, f) } } return missing } var headerParsers = map[string]HeaderP...
ke([]string, 0) for _, od := range ods { for _, h := range od.header { h.transfer.collectFriendly(&friendly) } } return friendly } func CollectMis
identifier_body
inter.go
contentLines []string) string { content := "" cl := 0 sort.Sort(RemarkSlice(rs.descriptors)) for _, ed := range rs.descriptors { if ed.line-cl >= 0 { content += strings.Join(contentLines[cl:ed.line], "\n") if ed.line-cl > 0 { content += "\n" } cl = ed.line + ed.skip } content += ed.Format() }...
mbed(
identifier_name
inter.go
content += "\n" } cl = ed.line + ed.skip } content += ed.Format() } content += strings.Join(contentLines[cl:], "\n") return content } func (rs *Remarks) Severity() int { return rs.severity } func (rs *Remarks) Histo(severity int) int { if severity >= 0 && severity <= MAX { return rs.histo[severity] ...
friendly []string } type snippetTransfer object func (vt *verbatimTransfer) collectFriendly(friendly *[]string) { } func (vt *verbatimTransfer) transfer(obj object, lookup map[string]object) { if vt.value == nil { delete(obj, vt.targetKey) } else { obj[vt.targetKey] = vt.value } } func (vs verbatimString) ...
type referenceTransfer struct { targetKey string
random_line_split
inter.go
content += "\n" } cl = ed.line + ed.skip } content += ed.Format() } content += strings.Join(contentLines[cl:], "\n") return content } func (rs *Remarks) Severity() int { return rs.severity } func (rs *Remarks) Histo(severity int) int { if severity >= 0 && severity <= MAX { return rs.histo[severity] ...
if len(values) >= 1 && values[len(values)-1] == "" { // handle empty list as well as trailing comma values = values[:len(values)-1] } return values } func (vl verbatimList) parse(value string) (HeaderTransfer, error) { return &verbatimTransfer{vl.targetKey, parseList(value)}, nil } func (rt *referenceTransfer...
values[i] = strings.TrimSpace(v) }
conditional_block
tab2.page.ts
.player = this.settings.player; } }); } openFile(file, index) { // tslint:disable-next-line:indent this.addView(file.id_pub); const media = { id_pub:file.id_pub, link_pub : file.link_pub, artist: file.nom_ent, title: file.nom, playing: true }; const n ...
{ if (this.onSeekState) { this.audioProvider.seekTo(event.target.value); this.play(); } else { this.audioProvider.seekTo(event.target.value); } }
identifier_body
tab2.page.ts
: any=[]; settings:any = { automatic:false, showImage:true, randomly:false, statistic:true, autoplay:false, cats:[], player:true } myUser = { type_login:1, user_data:{}, }; loader=false; users:any; DEV=true; private animator: AnimationBuilder; constructo...
} } } async presentToast(msg) { const toast = await this.toastController.create({ message: msg, duration: 3000 }); toast.present(); } setFormat(e){ if(e<1000){ return e+""; }else if (e>=1000 && e<999999){ return Math.ceil((e/1000))+"K"; } else if (e>=100000...
{ continue;}
conditional_block
tab2.page.ts
if(e<1000){ return e+""; }else if (e>=1000 && e<999999){ return Math.ceil((e/1000))+"K"; } else if (e>=1000000 && e<999999999){ return Math.ceil((e/1000000))+"M"; }else{ return "~"; } } async addView(id) { const data = await this.cloudProvider.addView('Bo/@Hb/addView/' + id).then(r...
random_line_split
tab2.page.ts
loader=false; users:any; DEV=true; private animator: AnimationBuilder; constructor( @Inject(FileTransfer) private transfer: FileTransfer, @Inject(File) private file: File, @Inject(ToastController) public toastController: ToastController, public navCtrl: NavController, public audioProvider: Aud...
events
identifier_name
model.rs
false => None, } } } #[allow(dead_code)] pub struct DxModel { // Window aspect_ratio: f32, // D3D12 Targets device: ComRc<ID3D12Device>, command_queue: ComRc<ID3D12CommandQueue>, swap_chain: ComRc<IDXGISwapChain3>, dc_dev: ComRc<IDCompositionDevice>, dc_target:...
{ let rc = self.item[self.index]; self.index += 1; Some(rc) }
conditional_block
model.rs
(window: &Window) -> Result<DxModel, HRESULT> { // window params let size = window.inner_size(); println!("inner_size={:?}", size); let hwnd = window.raw_window_handle(); let aspect_ratio = (size.width as f32) / (size.height as f32); let viewport = D3D12_VIEWPORT { ...
new
identifier_name
model.rs
the geometry for a circle. let items = (0..CIRCLE_SEGMENTS) .map(|i| { let a = 0 as UINT16; let b = (1 + i) as UINT16; let c = (2 + i) as UINT16; [a, b, c] }) .flat_map(|a| ArrayI...
_heap.as_ref(); let rtv_descriptor_size = self.rtv_descriptor_size; let viewport = &self.viewport; let scissor_rect = &self.scissor_rect; let render_targets = self.render_targets.as_slice(); let frame_index = self.frame_index as usize; let vertex_buffer_view = &self.verte...
identifier_body
model.rs
let texture = { let properties = D3D12_HEAP_PROPERTIES::new(D3D12_HEAP_TYPE_DEFAULT); device.create_committed_resource::<ID3D12Resource>( &properties, D3D12_HEAP_FLAG_NONE, &texture_desc, D3D12_RE...
Ok(()) } } // WAITING FOR THE FRAME TO COMPLETE BEFORE CONTINUING IS NOT BEST PRACTICE.
random_line_split
art_tree.go
} close(outChan) }() return outChan } // Finds the starting node for a prefix search and returns an array of all the objects under it func (t *ArtTree) PrefixSearch(key []byte) []interface{} { ret := make([]interface{}, 0) for r := range t.PrefixSearchChan(key) { ret = append(ret, r.Value) } return ret } fu...
else { t.removeHelper(*next, next, key, depth+1) } } // Convenience method for EachPreorder func (t *ArtTree) Each(callback func(*ArtNode)) { for n := range t.EachChanFrom(t.root) { callback(n) } } func (t *ArtTree) EachChan() chan *ArtNode { return t.EachChanFrom(t.root) } func (t *ArtTree) EachChanFrom(st...
{ current.RemoveChild(key[depth]) t.size -= 1 // Otherwise, recurse. t.size -= 1 }
conditional_block
art_tree.go
} close(outChan) }() return outChan } // Finds the starting node for a prefix search and returns an array of all the objects under it func (t *ArtTree) PrefixSearch(key []byte) []interface{} { ret := make([]interface{}, 0) for r := range t.PrefixSearchChan(key) { ret = append(ret, r.Value) } return ret } fu...
return current } // Check if our key mismatches the current compressed path prefixMismatch := current.PrefixMismatch(key, depth) if prefixMismatch == current.prefixLen { // whole prefix matches depth += current.prefixLen if depth > maxKeyIndex { return current } } else if prefixMismatch ==...
// Check if the current is a match (including prefix match) if current.IsLeaf() && len(current.key) >= len(key) && bytes.Equal(key, current.key[0:len(key)]) {
random_line_split
art_tree.go
} close(outChan) }() return outChan } // Finds the starting node for a prefix search and returns an array of all the objects under it func (t *ArtTree) PrefixSearch(key []byte) []interface{} { ret := make([]interface{}, 0) for r := range t.PrefixSearchChan(key) { ret = append(ret, r.Value) } return ret } fu...
// Returns the node that contains the passed in key, or nil if not found. func (t *ArtTree) Search(key []byte) interface{} { key = ensureNullTerminatedKey(key) foundNode := t.searchHelper(t.root, key, 0) if foundNode != nil && foundNode.IsMatch(key) { return foundNode.value } return nil } // Recursive search ...
{ return t.EachChanResultFrom(t.searchHelper(t.root, key, 0)) }
identifier_body
art_tree.go
} close(outChan) }() return outChan } // Finds the starting node for a prefix search and returns an array of all the objects under it func (t *ArtTree) PrefixSearch(key []byte) []interface{} { ret := make([]interface{}, 0) for r := range t.PrefixSearchChan(key) { ret = append(ret, r.Value) } return ret } fu...
(key []byte) { key = ensureNullTerminatedKey(key) t.removeHelper(t.root, &t.root, key, 0) } // Recursive helper for Removing child nodes. // There are two methods for removal: // // If the current node is a leaf and matches the specified key, remove it. // // If the next child at the specifed key and depth matches, ...
Remove
identifier_name
lib.rs
_remote_ip_on_rsp; #[allow(dead_code)] // TODO #2597 mod add_server_id_on_rsp; mod endpoint; mod orig_proto_upgrade; mod require_identity_on_endpoint; mod resolve; pub use self::endpoint::Endpoint; pub use self::resolve::resolve; const EWMA_DEFAULT_RTT: Duration = Duration::from_millis(30); const EWMA_DECAY: Duration...
<A, R, P>( config: &Config, local_identity: tls::Conditional<identity::Local>, listen: transport::Listen<A>, resolve: R, dns_resolver: dns::Resolver, profiles_client: linkerd2_app_core::profiles::Client<P>, tap_layer: linkerd2_app_core::tap::Layer, handle_time: http_metrics::handle_time:...
spawn
identifier_name
lib.rs
1. Records http metrics with per-endpoint labels. // 2. Instruments `tap` inspection. // 3. Changes request/response versions when the endpoint // supports protocol upgrade (and the request may be upgraded). // 4. Appends `l5d-server-id` to responses coming back iff meshed // TLS was used on ...
{ transport::labels::Key::connect("outbound", endpoint.identity.as_ref()) }
identifier_body
lib.rs
_remote_ip_on_rsp; #[allow(dead_code)] // TODO #2597 mod add_server_id_on_rsp; mod endpoint; mod orig_proto_upgrade; mod require_identity_on_endpoint; mod resolve; pub use self::endpoint::Endpoint; pub use self::resolve::resolve; const EWMA_DEFAULT_RTT: Duration = Duration::from_millis(30); const EWMA_DECAY: Duration...
// // This is shared across addr-stacks so that multiple addrs that // canonicalize to the same DstAddr use the same dst-stack service. let dst_router = dst_stack .push(trace::layer( |dst: &DstAddr| info_span!("logical", dst.logical = %dst.dst_logical()), )) .push_buf...
// Routes request using the `DstAddr` extension.
random_line_split
lib.rs
.mdns.eu/nextcloud/passwords/wikis/Developers/Api/Token-Api) pub mod token; // TODO: sort the session required methods from the non-session required mod utils; pub use utils::{QueryKind, SearchQuery}; mod private { pub trait Sealed {} impl Sealed for super::settings::UserSettings {} impl Sealed for supe...
{ status: String, id: u64, message: String, } #[derive(Serialize, Deserialize)] #[serde(untagged)] pub enum EndpointResponse<T> { Error(EndpointError), Success(T), } /// Represent how to first connect to a nextcloud instance /// The best way to obtain some is using [Login flow /// v2](https://doc...
EndpointError
identifier_name
lib.rs
)] pub struct LoginDetails { pub server: Url, #[serde(rename = "loginName")] pub login_name: String, #[serde(rename = "appPassword")] pub app_password: String, } impl LoginDetails { /// Login with the login flow v2 to the server. The `auth_callback` is given the URL where the /// user will ...
Ok((api, session_id)) }
random_line_split
infinite-article-origin.js
$('.inStreamAd', target) .append('<div class="ad_label">Advertisement</div>') .append($iframe); } }, /** * Creates an ad call that goes with DFP ad server * @param {Object}} target jQu...
{ articleInfinite.opts.container.trigger('disableInfinite'); return; }
conditional_block
infinite-article-origin.js
if (i && !h) { l() } h && clearTimeout(h); if (i === c && m > e) { l() } else { if (f !== true) { h = setTimeout(i ? k : l, i === c ? e - m : e) } } } ...
{ h = c }
identifier_body
infinite-article-origin.js
section.page:last').data('page-number'); /** * Loop through all the pages and add an Ad container to them * This lets us easily give the container an ID to target them * later. COULD PROB BE IN THE XSL, but we did it here bc * the numb...
* ---- IT'S CURRENTLY THE DEFAULT ---- */ nonAjaxCall: function () {
random_line_split
infinite-article-origin.js
() { var o = this, m = +new Date() - d, n = arguments; function l() { d = +new Date(); j.apply(o, n) } function k() { h = c } if (i && !h) { l() } h && clear...
g
identifier_name
main.rs
fn flow_down(&mut self, y: usize, x: usize) -> (usize, usize) { for yf in y+1 .. self.data.len() { if self.data[yf][x] == Tile::Sand { self.data[yf][x] = Tile::Water; } else if self.data[yf][x] != Tile::Water { return (yf - 1, x); } ...
{ data[0][500 - xstart + 2] = Tile::Spring; Map { data, xstart } }
identifier_body
main.rs
Sand { self.data[yf][x] = Tile::Water; } else if self.data[yf][x] != Tile::Water { return (yf - 1, x); } } (self.data.len(), x) } fn check_enclosed(&self, y: usize, x: usize) -> (Option<usize>, Option<usize>) { // Check left ...
(&self, c: &Self::Coord) -> &Self::Tile { &self.data[c.y()][c.x()] } } impl sg::GridTile for Tile { fn to_char(&self) -> char { match self { Tile::Clay => '#', Tile::Sand => '.', Tile::Spring => '+', Tile::Water => '|', Tile::WaterAtRe...
tile_at
identifier_name
main.rs
::Sand { self.data[yf][x] = Tile::Water; } else if self.data[yf][x] != Tile::Water { return (yf - 1, x); } } (self.data.len(), x) } fn check_enclosed(&self, y: usize, x: usize) -> (Option<usize>, Option<usize>) { // Check left
let (mut enclosed_left, mut enclosed_right) = (None, None); for xf in (0..x).rev() { if self.data[y][xf] == Tile::Clay || self.data[y + 1][xf] == Tile::Sand { enclosed_left = Some(xf + 1); break; } } fo...
random_line_split
manager_test.go
So(pmNotifier.UpdateConfig(ctx, lProject), ShouldBeNil) So(pmtest.Projects(ct.TQ.Tasks()), ShouldResemble, []string{lProject}) events1, err := eventbox.List(ctx, recipient) So(err, ShouldBeNil) // Simulate stuck TQ task, which gets executed with a huge delay. ct.Clock.Add(time.Hour) ct.TQ.Run(ctx, tqtest...
{ t.Parallel() Convey("PM task does nothing if it comes too late", t, func() { ct := cvtesting.Test{} ctx, cancel := ct.SetUp() defer cancel() pmNotifier := prjmanager.NewNotifier(ct.TQDispatcher) runNotifier := runNotifierMock{} clMutator := changelist.NewMutator(ct.TQDispatcher, pmNotifier, &runNotifi...
identifier_body
manager_test.go
Entities(ctx, lProject) So(p.EVersion, ShouldEqual, 1) So(ps.Status, ShouldEqual, prjpb.Status_STARTED) So(plog, ShouldNotBeNil) So(poller.FilterProjects(ct.TQ.Tasks().SortByETA().Payloads()), ShouldResemble, []string{lProject}) // Ensure first poller task gets executed. ct.Clock.Add(time.Hour) C...
{ So(pmNotifier.UpdateConfig(ctx, lProject), ShouldBeNil) So(pmNotifier.Poke(ctx, lProject), ShouldBeNil) // Simulate updating a CL. cl44.EVersion++ So(datastore.Put(ctx, cl44), ShouldBeNil) So(pmNotifier.NotifyCLsUpdated(ctx, lProject, changelist.ToUpdatedEvents(cl44)), ShouldBeNil) }
conditional_block
manager_test.go
clMutator := changelist.NewMutator(ct.TQDispatcher, pmNotifier, &runNotifier, &tjMock{}) clUpdater := changelist.NewUpdater(ct.TQDispatcher, clMutator) gerritupdater.RegisterUpdater(clUpdater, ct.GFactory()) pm := New(pmNotifier, &runNotifier, clMutator, ct.GFactory(), clUpdater) cfg := singleRepoConfig(gHost...
popUpdateConfig
identifier_name
manager_test.go
3) So(ps.Status, ShouldEqual, prjpb.Status_STOPPING) So(plog, ShouldNotBeNil) So(poller.FilterProjects(ct.TQ.Tasks().SortByETA().Payloads()), ShouldResemble, []string{lProject}) // Should ask Runs to cancel themselves. reqs := make([]cancellationRequest, len(p.IncompleteRuns())) for i, run...
random_line_split
point.js
UIClass.prototype = Object.create(baseProgram.prototype); UIClass.prototype = { "getNameSpace":function() { //need to look back to find 'grid' location }, "mouseClickCallback":function(ptr) { // iterate through the next pieces... }, "evaluateNode":function(pcj) { var hier = graph.prototype.getVal...
selectInternodeDescendants
identifier_name
point.js
{ //a.pop(); a.pop(); var o = getObject(a, graphLookup); if (o.types['root']) { //if (o.value != this.progs[this.progs.length-1]) { this.rootName = o.node.value; //.push(o); //break; //} } if (o.types['program']) { this.programs.push(this.node.value); } } }, } function Syst...
{ }
identifier_body
point.js
ier, {'row':{'label':[{'text':'save as'}, {'inputbox':'text'}, {'button':'type'}]}}); console.log("x:"+x); return; var hl = hier.length-1; if (this.node.types) if (this.node['types']["root"]) { // if (hier[hl] == "UI") { // if (this.phraseBegin) // this.ptrProgs[this.id] = new UIProgram(this.id, gr...
{ var link = obj[i]; //if (link.parents[0].length || link.children[0].length) this.descendants.push(obj[i].children.concat(obj[i].parents)); //return ptr; }
conditional_block
point.js
for (var i =0 ; i < nextPtrs.length; i++) { console.log("-----xxxx-----"); //var tpg = programs[this.programName]; //function pt() { }; //pt.prototype = Object.create(point.prototype); // mixin(pt.prototype, programComponents.prototype); // mixin(pt.prototype, tpg.prototype); //pt.constructor = point.pr...
if (a1.types['program']) this.programName = nodeName;
random_line_split
lib.rs
collect(); // Create shared references to each account's lamports/data/owner let account_refs: HashMap<_, _> = accounts .iter_mut() .map(|(key, account)| { ( *key, ( Rc::new(RefCell::new(&mut account.lamports)), ...
(other_invoke_context: &RefCell<Rc<MockInvokeContext>>) { INVOKE_CONTEXT.with(|invoke_context| { invoke_context.swap(&other_invoke_context); }); } struct SyscallStubs {} impl program_stubs::SyscallStubs for SyscallStubs { fn sol_log(&self, message: &str) { INVOKE_CONTEXT.with(|invoke_contex...
swap_invoke_context
identifier_name
lib.rs
account.lamports = **lamports.borrow(); account.data = data.borrow().to_vec(); } } swap_invoke_context(&local_invoke_context); // Propagate logs back to caller's invoke context // (TODO: This goes away if MockInvokeContext usage can be removed) let logger = invoke_context.get_...
{ let mut me = Self::default(); me.add_program(program_name, program_id, process_instruction); me }
identifier_body
lib.rs
InvokeContext more, or rework to avoid MockInvokeContext entirely. // The context being passed into the program is incomplete... }); if instruction.accounts.len() + 1 != account_infos.len() { panic!( "Instruction accounts mismatch. Instruction contains {} ...
}
random_line_split
utils.rs
trait Samples<'a, T: 'a>: Sized { /// Call the given closure for each sample of the given channel. // FIXME: Workaround for TrustedLen / TrustedRandomAccess being unstable // and because of that we wouldn't get nice optimizations fn foreach_sample(&self, channel: usize, func: impl FnMut(&'a T)); /...
self.data.len() } #[inline] fn split_at(self, sample: usize) -> (Self, Self) { assert!(self.start + sample <= self.end); ( Planar { data: self.data, start: self.start, end: self.start + sample, }, P...
fn channels(&self) -> usize {
random_line_split
utils.rs
a new wrapper around the planar channels and do a sanity check. pub fn new(data: &'a [&'a [T]]) -> Result<Self, crate::Error> { if data.is_empty() { return Err(crate::Error::NoMem); } if data.iter().any(|d| data[0].len() != d.len()) { return Err(crate::Error::NoMem)...
xt(&
identifier_name
utils.rs
trait Samples<'a, T: 'a>: Sized { /// Call the given closure for each sample of the given channel. // FIXME: Workaround for TrustedLen / TrustedRandomAccess being unstable // and because of that we wouldn't get nice optimizations fn foreach_sample(&self, channel: usize, func: impl FnMut(&'a T)); /...
impl AsF32 for f64 { #[inline] fn as_f32_scaled(self) -> f32 { self as f32 } } /// Trait for converting samples into f64 in the range [0,1]. pub trait AsF64: AsF32 + Copy + PartialOrd { const MAX: f64; fn as_f64(self) -> f64; #[inline] fn as_f64_scaled(self) -> f64 { sel...
self } }
identifier_body
utils.rs
T> for Planar<'a, T> { #[inline] fn foreach_sample(&self, channel: usize, mut func: impl FnMut(&'a T)) { assert!(channel < self.data.len()); for v in &self.data[channel][self.start..self.end] { func(v) } } #[inline] fn foreach_sample_zipped<U>( &self, ...
self.seed.channels as usize } e
conditional_block
libstore-impl.go
port to an RPC client object cache map[string]interface{} // maps a key to a cached value getrequests map[string][]time.Time // maps a key to a list of times it has been Get requested // Basic parameters flags int myhostport string // Synchronization channels syncopchan chan *syncop clireplyc...
if err != nil { fmt.Printf("Could not connect to server %s, returning nil\n", hostport) fmt.Printf("Error: %s\n", err.Error()) return nil, err } ls.rpcclis[hostport] = cli } return cli, nil } // Return RPC client of server corresponding to the key func (ls *Libstore) getServer(key string) (*rpc.Client...
var err error cli, err = rpc.DialHTTP("tcp", hostport)
random_line_split
libstore-impl.go
ls.nodelist = reply.Servers // Sort the nodes by NodeID in ascending order sort.Sort(ls.nodelist) // Start the synchronized operation handler go ls.handleSyncOps() // Register RevokeLease method with RPC crpc := cacherpc.NewCacheRPC(ls) rpc.Register(crpc) return ls, nil } <-ticker.C } ...
RevokeLease
identifier_name
libstore-impl.go
args := storageproto.GetServersArgs{} var reply storageproto.RegisterReply ticker := time.NewTicker(RETRY_INTERVAL) for retryCount := 0; retryCount < RETRY_LIMIT; retryCount++ { err = cli.Call("StorageRPC.GetServers", args, &reply) if err != nil { return nil, err } if reply.Ready && reply.Servers != ni...
{ args := &storageproto.PutArgs{key, newitem} var reply storageproto.PutReply cli, err := ls.getServer(key) if err != nil { return err } err = cli.Call("StorageRPC.AppendToList", args, &reply) if err != nil { return err } if reply.Status != storageproto.OK { return lsplog.MakeErr("AppendToList failed: S...
identifier_body
libstore-impl.go
[string][]time.Time) ls.syncopchan = make(chan *syncop) ls.clireplychan = make(chan *rpccli) ls.cachereplychan = make(chan *cachevalue) ls.successreplychan = make(chan bool) // Create RPC connection to storage server cli, err := rpc.DialHTTP("tcp", server) if err != nil { fmt.Printf("Could not connect to ser...
{ return err }
conditional_block
router.rs
}, next_config::NextConfigVc, next_edge::{ context::{get_edge_compile_time_info, get_edge_resolve_options_context}, transition::NextEdgeTransition, }, next_import_map::get_next_build_import_map, next_server::context::{get_server_module_options_context, ServerContextType}, util::{...
route_internal
identifier_name
router.rs
)] #[serde(rename_all = "camelCase")] pub struct RouterRequest { pub method: String, pub pathname: String, pub raw_query: String, pub raw_headers: Vec<(String, String)>, } #[turbo_tasks::value(shared)] #[derive(Debug, Clone, Default)] #[serde(rename_all = "camelCase")] pub struct RewriteResponse { ...
}; let result = evaluate( router_asset, project_path, env,
random_line_split
minimize.rs
W: WeaklyDivisibleSemiring + WeightQuantize, W::ReverseWeight: WeightQuantize, { let delta = config.delta; let allow_nondet = config.allow_nondet; let props = ifst.compute_and_update_properties( FstProperties::ACCEPTOR | FstProperties::I_DETERMINISTIC | FstProperties...
/// and also non-deterministic ones if they use an idempotent semiring. /// For transducers, the algorithm produces a compact factorization of the minimal transducer. pub fn minimize_with_config<W, F>(ifst: &mut F, config: MinimizeConfig) -> Result<()> where F: MutableFst<W> + ExpandedFst<W> + AllocableFst<W>,
random_line_split
minimize.rs
ISTIC) { true } else { if !W::properties().contains(SemiringProperties::IDEMPOTENT) { bail!("Cannot minimize a non-deterministic FST over a non-idempotent semiring") } else if !allow_nondet { bail!("Refusing to minimize a non-deterministic FST with allow_nondet = fals...
<W: Semiring, F: MutableFst<W> + ExpandedFst<W>>( ifst: &mut F, allow_acyclic_minimization: bool, ) -> Result<()> { let props = ifst.compute_and_update_properties( FstProperties::ACCEPTOR | FstProperties::UNWEIGHTED | FstProperties::ACYCLIC, )?; if !props.contains(FstProperties::ACCEPTOR | F...
acceptor_minimize
identifier_name
minimize.rs
ISTIC)
else { if !W::properties().contains(SemiringProperties::IDEMPOTENT) { bail!("Cannot minimize a non-deterministic FST over a non-idempotent semiring") } else if !allow_nondet { bail!("Refusing to minimize a non-deterministic FST with allow_nondet = false") } fals...
{ true }
conditional_block
state_machine.go
OnInput func // until Complete returns true. // // A note on error handling: errors should be logged but are not // propogated up to the user. Due to the preferred style of thin // States, you should generally avoid logging errors directly in // the OnInput function and instead log them within any called functio...
Reset
identifier_name
state_machine.go
can be sure, for example, that the user has selected some // products and picked a shipping address before arriving at the // checkout step. In the case where one of the jumped Complete() // functions returns false, the state machine will stop at that state, // i.e. as close to the desired state as possible. Labe...
random_line_split
state_machine.go
// OnInput sets the category in the cache/DB. Note that if invalid, this // state's Complete function will return false, preventing the user from // continuing. User messages will continue to hit this OnInput func // until Complete returns true. // // A note on error handling: errors should be logged but are no...
if h.SkipIfComplete { if done { sm.plugin.Log.Debug("state was complete. moving on") sm.state++ sm.plugin.SetMemory(in, StateKey, sm.state) return sm.Next(in) } } sm.setEntered(in) sm.plugin.Log.Debug("setting state entered") // If this is the final state and complete on entry, we'll ...
{ // This check prevents a panic when no states are being used. if len(sm.Handlers) == 0 { return } sm.LoadState(in) // This check prevents a panic when a plugin has been modified to remove // one or more states. if sm.state >= len(sm.Handlers) { sm.plugin.Log.Debug("state is >= len(handlers)") sm.Reset(...
identifier_body
state_machine.go
// OnInput sets the category in the cache/DB. Note that if invalid, this // state's Complete function will return false, preventing the user from // continuing. User messages will continue to hit this OnInput func // until Complete returns true. // // A note on error handling: errors should be logged but are not ...
sm.setEntered(in) str = sm.Handlers[sm.state].OnEntry(in) sm.plugin.Log.Debug("going to next state", sm.state) return str } sm.plugin.Log.Debug("set state to", sm.state) sm.plugin.Log.Debug("set state entered to", sm.stateEntered) return str } // setEntered is used internally to set a state as having bee...
{ sm.plugin.Log.Debug("finished states. resetting") sm.Reset(in) return sm.Next(in) }
conditional_block
gfx2.go
-Fensters // ist geliefert. // Grafikzeilen () uint16 // Vor.: Das Grafikfenster ist offen. // Erg.: Die Anzahl der Grafikfensterspalten (Pixelspalten) des gfx2-Fensters // ist geliefert. // Grafikspalten () uint16 // Vor.: Das Grafikfenster ist offen. // Eff.: Das gfx-Fenster hat sichtbar den n...
// Winkelmaß von 0 Grad bedeutet in Richtung Osten geht es los, dann // entgegengesetzt zum Uhrzeigersinn. // Kreissektor (x,y,r,w1,w2 uint16) // Vor.: Das Grafikfenster ist offen. // Eff.: Um den Mittelpunkt M (x,y) ist mit dem Radius r in der aktuellen // Stiftfarbe ein gefüllter Kreissegme...
random_line_split
diag.rs
, PartialEq, Eq)] pub enum Severity { Remark, Info, Warning, Error, Fatal, } impl Severity { /// Get the color corresponding to this severity. fn color(&self) -> Color { match self { Severity::Remark => Color::Blue, Severity::Info => Color::Black, ...
/// Clear exsting diagnostics
{ self.report(Diagnostic::new(Severity::Fatal, msg.into(), span)); std::panic::panic_any(Severity::Fatal); }
identifier_body
diag.rs
Copy, PartialEq, Eq)] pub enum Severity { Remark, Info, Warning, Error, Fatal, } impl Severity { /// Get the color corresponding to this severity. fn color(&self) -> Color { match self { Severity::Remark => Color::Blue, Severity::Info => Color::Black, ...
} } // Reserve a column for end-of-line character columns.push(vlen + 1); VisualString { str: vstr, columns: columns, } } fn visual_column(&self, pos: usize) -> usize { self.columns[pos] } fn visual_length(&self) -> ...
} for _ in 0..ch.len_utf8() { columns.push(vlen);
random_line_split
diag.rs
Copy, PartialEq, Eq)] pub enum Severity { Remark, Info, Warning, Error, Fatal, } impl Severity { /// Get the color corresponding to this severity. fn color(&self) -> Color { match self { Severity::Remark => Color::Blue, Severity::Info => Color::Black, ...
(&self, diag: Diagnostic) { let mut m = self.mutable.borrow_mut(); diag.print(&m.src, true, 4); m.diagnostics.push(diag); } /// Create a errpr diagnostic from message and span and report it. pub fn report_span<M: Into<String>>(&self, severity: Severity, msg: M, span: Span) { ...
report
identifier_name
lib.rs
//! // .. //! } //! ``` #[cfg(target_os = "android")] extern crate android_log_sys as log_ffi; #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; use std::sync::RwLock; #[cfg(target_os = "android")] use log_ffi::LogPriority; use log::{Level, Log, Metadata, Record}; use std::ffi::CStr; use std:...
/// Set multiple allowed module paths. /// /// Same as `with_allowed_module_path`, but accepts list of paths. /// /// ## Example: /// /// ``` /// use android_logger::Filter; /// /// let filter = Filter::default() /// .with_allowed_module_paths(["A", "B"].iter().map(|i| ...
{ self.allow_module_paths.push(path.into()); self }
identifier_body
lib.rs
//! //! // .. //! } //! ``` #[cfg(target_os = "android")] extern crate android_log_sys as log_ffi; #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; use std::sync::RwLock; #[cfg(target_os = "android")] use log_ffi::LogPriority; use log::{Level, Log, Metadata, Record}; use std::ffi::CStr; use ...
(_priority: Level, _tag: &CStr, _msg: &CStr) {} /// Underlying android logger backend pub struct AndroidLogger { filter: RwLock<Filter>, } lazy_static! { static ref ANDROID_LOGGER: AndroidLogger = AndroidLogger::default(); } const LOGGING_TAG_MAX_LEN: usize = 23; const LOGGING_MSG_MAX_LEN: usize = 4000; impl...
android_log
identifier_name
lib.rs
ptr; /// Output log to android system. #[cfg(target_os = "android")] fn android_log(prio: log_ffi::LogPriority, tag: &CStr, msg: &CStr) { unsafe { log_ffi::__android_log_write( prio as log_ffi::c_int, tag.as_ptr() as *const log_ffi::c_char, msg.as_ptr() as *const log_ffi...
*unsafe { self.buffer.get_unchecked_mut(len) } = last_byte;
random_line_split
lib.rs
} } impl Log for AndroidLogger { fn enabled(&self, _: &Metadata) -> bool { true } fn log(&self, record: &Record) { if let Some(module_path) = record.module_path() { let filter = self.filter .read() .expect("failed to acquire android_log filter l...
{ acc }
conditional_block
dss.go
is a data structure for a linear stack within a DSS (DAG structured stack = DSS). // All stacks together form a DSS, i.e. they // may share portions of stacks. Each client carries its own stack, without // noticing the other stacks. The data structure hides the fact that stack- // fragments may be shared. type Stack s...
T().Debugf("reducing node %v (now cnt=%d)", node, node.pathcnt) T().Debugf(" node %v has %d succs", node, len(node.succs))
random_line_split
dss.go
func (n *DSSNode) successorCount() int { if n.succs != nil { return len(n.succs) } return 0 } func (n *DSSNode) predecessorCount() int { if n.preds != nil { return len(n.preds) } return 0 } func (n *DSSNode) findUplink(sym lr.Symbol) *DSSNode { s := contains(n.succs, sym) return s } func (n *DSSNode) f...
{ return n.succs != nil && len(n.succs) > 1 }
identifier_body
dss.go
stack.FindHandlePath(handle, skip) } destructive := stack.IsAlone() // give general permission to delete reduced nodes? for _, path = range paths { // now reduce along every path stacks := stack.reduce(path, destructive) ret = append(ret, stacks...) // collect returned stack heads } if len(ret) > 0 { // if...
{ return n }
conditional_block
dss.go
if n.preds != nil { return len(n.preds) } return 0 } func (n *DSSNode) findUplink(sym lr.Symbol) *DSSNode { s := contains(n.succs, sym) return s } func (n *DSSNode) findDownlink(state int) *DSSNode { s := hasState(n.preds, state) return s } // NodePath is a run within a stack. We often will have to deal wit...
() string { return fmt.Sprintf("stack{tos=%v}", stack.tos) } // Calculate the height of a stack /* func (stack *Stack) calculateHeight() { stack.height = stack.tos.height(stack.root.bottom) // recurse until hits bottom } func (node *DSSNode) height(stopper *DSSNode) int { if node == stopper { return 0 } max :=...
String
identifier_name
tags.rs
fn add_class(&mut self, class: &str) { let attr = self.attribute("class"); let mut attr = if let Some(s) = attr { s } else { String::with_capacity(class.len()) }; attr.push(' '); attr.push_str(class); self.set_attribute("class", &attr); ...
{ if let Some(s) = self.attribute("href") { s } else { String::new() } }
identifier_body