file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
distributed_dqn_v2.py
# Chih-Hsiang Wamg # 2019/6/2 import gym import torch import time import os import ray import numpy as np import csv from tqdm import tqdm from random import uniform, randint import io import base64 from IPython.display import HTML from dqn_model import DQNModel from dqn_model import _DQNModel from memory import Re...
# =================== 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 def update_batch(self): batch = ray.get(self.memory_server.sample.rem...
def __init__(self, env, hyper_params, action_space = len(ACTION_DICT)): self.env = env self.max_episode_steps = env._max_episode_steps """ beta: The discounted factor of Q-value function (epsilon): The explore or exploit policy epsilon. initial_epsil...
identifier_body
distributed_dqn_v2.py
# Chih-Hsiang Wamg # 2019/6/2 import gym import torch import time import os import ray import numpy as np import csv from tqdm import tqdm from random import uniform, randint import io import base64 from IPython.display import HTML from dqn_model import DQNModel from dqn_model import _DQNModel from memory import Re...
(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
# Chih-Hsiang Wamg # 2019/6/2 import gym import torch import time import os import ray import numpy as np import csv from tqdm import tqdm from random import uniform, randint import io import base64 from IPython.display import HTML from dqn_model import DQNModel from dqn_model import _DQNModel from memory import Re...
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
# Chih-Hsiang Wamg # 2019/6/2 import gym import torch import time import os import ray import numpy as np import csv from tqdm import tqdm from random import uniform, randint import io import base64 from IPython.display import HTML from dqn_model import DQNModel from dqn_model import _DQNModel from memory import Re...
@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
use std::collections::{HashMap, HashSet}; use std::fs; use std::path::PathBuf; use std::process; use std::str::FromStr; use std::sync::{mpsc::Sender, Arc, Mutex}; use std::thread; use std::time::{Duration, Instant}; use zellij_utils::{serde, zellij_tile}; use serde::{de::DeserializeOwned, Serialize}; use wasmer::{ ...
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
use std::collections::{HashMap, HashSet}; use std::fs; use std::path::PathBuf; use std::process; use std::str::FromStr; use std::sync::{mpsc::Sender, Arc, Mutex}; use std::thread; use std::time::{Duration, Instant}; use zellij_utils::{serde, zellij_tile}; use serde::{de::DeserializeOwned, Serialize}; use wasmer::{ ...
{ 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
use std::collections::{HashMap, HashSet}; use std::fs; use std::path::PathBuf; use std::process; use std::str::FromStr; use std::sync::{mpsc::Sender, Arc, Mutex}; use std::thread; use std::time::{Duration, Instant}; use zellij_utils::{serde, zellij_tile}; use serde::{de::DeserializeOwned, Serialize}; use wasmer::{ ...
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
use std::collections::{HashMap, HashSet}; use std::fs; use std::path::PathBuf; use std::process; use std::str::FromStr; use std::sync::{mpsc::Sender, Arc, Mutex}; use std::thread; use std::time::{Duration, Instant}; use zellij_utils::{serde, zellij_tile}; use serde::{de::DeserializeOwned, Serialize}; use wasmer::{ ...
} 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
use std::any::type_name; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use cosmwasm_std::{Api, CanonicalAddr, ReadonlyStorage, StdError, StdResult, Storage}; use cosmwasm_storage::{PrefixedStorage, ReadonlyPrefixedStorage}; use secret_toolkit::{ serialization::{Bincode2, Serde}, storage::{Appen...
(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
use std::any::type_name; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use cosmwasm_std::{Api, CanonicalAddr, ReadonlyStorage, StdError, StdResult, Storage}; use cosmwasm_storage::{PrefixedStorage, ReadonlyPrefixedStorage}; use secret_toolkit::{ serialization::{Bincode2, Serde}, storage::{Appen...
/// * `api` - a reference to the Api used to convert human and canonical addresses /// * `storage` - a reference to the contract's storage /// * `address` - a reference to the address whose battles to display /// * `page` - page to start displaying /// * `page_size` - number of txs per page pub fn get_history<A: Api, S...
/// Returns StdResult<Vec<Battle>> of the battles to display /// /// # Arguments ///
random_line_split
state.rs
use std::any::type_name; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use cosmwasm_std::{Api, CanonicalAddr, ReadonlyStorage, StdError, StdResult, Storage}; use cosmwasm_storage::{PrefixedStorage, ReadonlyPrefixedStorage}; use secret_toolkit::{ serialization::{Bincode2, Serde}, storage::{Appen...
} /// 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
use std::any::type_name; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use cosmwasm_std::{Api, CanonicalAddr, ReadonlyStorage, StdError, StdResult, Storage}; use cosmwasm_storage::{PrefixedStorage, ReadonlyPrefixedStorage}; use secret_toolkit::{ serialization::{Bincode2, Serde}, storage::{Appen...
else { return Ok(vec![]); }; let config: Config = load(storage, CONFIG_KEY)?; let versions = config .card_versions .iter() .map(|v| v.to_humanized(api)) .collect::<StdResult<Vec<ContractInfo>>>()?; // access battle storage let his_store = ReadonlyPrefixedStor...
{ result? }
conditional_block
testingfrog.rs
#![allow(dead_code)] #![allow(unused_variables)] #![allow(unreachable_code)] #![allow(unused_imports)] #![allow(clippy::all)] //**************************************** // tracing test //**************************************** // use axum::{routing::get, Router}; // use std::error::Error; // // use tracing_subscriber...
// loop { // match prev { // Some(v) => match self.rx.recv_timeout(self.d) { // Ok(newval) => { // prev = Some(newval); // continue; // } // Err(_) => break Ok(v), // ...
// // impl<T> Debounced<T> { // fn recv(&self) -> Result<T, mpsc::RecvError> { // let mut prev = None; //
random_line_split
testingfrog.rs
#![allow(dead_code)] #![allow(unused_variables)] #![allow(unreachable_code)] #![allow(unused_imports)] #![allow(clippy::all)] //**************************************** // tracing test //**************************************** // use axum::{routing::get, Router}; // use std::error::Error; // // use tracing_subscriber...
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
#![allow(dead_code)] #![allow(unused_variables)] #![allow(unreachable_code)] #![allow(unused_imports)] #![allow(clippy::all)] //**************************************** // tracing test //**************************************** // use axum::{routing::get, Router}; // use std::error::Error; // // use tracing_subscriber...
(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
//! This module supports synchronizing a UPM database with a copy on a remote repository. The //! remote repository should be an HTTP or HTTPS server supporting the "download", "upload", and //! "delete" primitives of the UPM sync protocol. use reqwest::multipart; use std::io::Read; use std::path::{Path, PathBuf}; us...
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
//! This module supports synchronizing a UPM database with a copy on a remote repository. The //! remote repository should be an HTTP or HTTPS server supporting the "download", "upload", and //! "delete" primitives of the UPM sync protocol. use reqwest::multipart; use std::io::Read; use std::path::{Path, PathBuf}; us...
(&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
//! This module supports synchronizing a UPM database with a copy on a remote repository. The //! remote repository should be an HTTP or HTTPS server supporting the "download", "upload", and //! "delete" primitives of the UPM sync protocol. use reqwest::multipart; use std::io::Read; use std::path::{Path, PathBuf}; us...
{ // 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
import os import numpy as np import pandas as pd from scvi.dataset import GeneExpressionDataset from scvi.models import VAE from scvi.inference import UnsupervisedTrainer import torch import anndata import plotly.graph_objects as go import io import requests import urllib from io import StringIO import boto3 import dat...
logs = open('log_file.txt', 'r').read() logs_buffer = StringIO() logs_buffer.write(logs) csv_buffer = StringIO() logsfilename = 'logs/' + filename + '-logs.txt' print(' ### ### ### Putting log in s3...') client = boto3.client('s3', aws_access_key_id=AWS_S3_ACCE...
filename = filename.replace('.csv', '')
random_line_split
de.py
import os import numpy as np import pandas as pd from scvi.dataset import GeneExpressionDataset from scvi.models import VAE from scvi.inference import UnsupervisedTrainer import torch import anndata import plotly.graph_objects as go import io import requests import urllib from io import StringIO import boto3 import dat...
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
/* * COMP3801 Winter 2017 Lab 5 * * Scene object - define model placement in world coordinates */ /* * Constructor for Scene object. This object holds a list of models to render, * and a transform for each one. The list is defined in a JSON file. The * field named "models" in the JSON file defines the list....
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
/* * COMP3801 Winter 2017 Lab 5 * * Scene object - define model placement in world coordinates */ /* * Constructor for Scene object. This object holds a list of models to render, * and a transform for each one. The list is defined in a JSON file. The * field named "models" in the JSON file defines the list....
(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
/* * COMP3801 Winter 2017 Lab 5 * * Scene object - define model placement in world coordinates */ /* * Constructor for Scene object. This object holds a list of models to render, * and a transform for each one. The list is defined in a JSON file. The * field named "models" in the JSON file defines the list....
; var hasReached = true; var lastPosition = 0; var etol = 0; var rotX = 0; var rotY = 0; Scene.prototype.Render = function() { var gl = this.gl; gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); var camera = this.camera; // Compute aspect ratio of canvas var aspect = this.canvas.width / this.canvas.he...
{ // 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
/* * COMP3801 Winter 2017 Lab 5 * * Scene object - define model placement in world coordinates */ /* * Constructor for Scene object. This object holds a list of models to render, * and a transform for each one. The list is defined in a JSON file. The * field named "models" in the JSON file defines the list....
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
package main import ( "bytes" "crypto/md5" "encoding/hex" "encoding/json" "errors" "expvar" "flag" "fmt" "io/ioutil" "net" "net/http" "os" "path" "strings" "sync" "time" graphite "github.com/cyberdelia/go-metrics-graphite" "github.com/facebookgo/pidfile" "github.com/rcrowley/go-metrics" "github.co...
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
package main import ( "bytes" "crypto/md5" "encoding/hex" "encoding/json" "errors" "expvar" "flag" "fmt" "io/ioutil" "net" "net/http" "os" "path" "strings" "sync" "time" graphite "github.com/cyberdelia/go-metrics-graphite" "github.com/facebookgo/pidfile" "github.com/rcrowley/go-metrics" "github.co...
} 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
package main import ( "bytes" "crypto/md5" "encoding/hex" "encoding/json" "errors" "expvar" "flag" "fmt" "io/ioutil" "net" "net/http" "os" "path" "strings" "sync" "time" graphite "github.com/cyberdelia/go-metrics-graphite" "github.com/facebookgo/pidfile" "github.com/rcrowley/go-metrics" "github.co...
func startOutputs() error { // Configure the specific output. // Valid options are: 'udp', 'tcp', 'file', 's3', 'syslog' ,"http",'splunk' var outputHandler OutputHandler parameters := config.OutputParameters switch config.OutputType { case FileOutputType: outputHandler = &FileOutput{} case TCPOutputType: ...
{ 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
package main import ( "bytes" "crypto/md5" "encoding/hex" "encoding/json" "errors" "expvar" "flag" "fmt" "io/ioutil" "net" "net/http" "os" "path" "strings" "sync" "time" graphite "github.com/cyberdelia/go-metrics-graphite" "github.com/facebookgo/pidfile" "github.com/rcrowley/go-metrics" "github.co...
(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
''' imports reading list from mangaupdates.com to mangadex.org requires: beautifulsoup4 chromedriver-binary (to be installed in python3 directory) PyYAML selenium ./credentials.yaml mu_username: <account name> mu_password: <password> md_username:<account name> md_password: <password> ''' from bs4 import BeautifulSou...
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
''' imports reading list from mangaupdates.com to mangadex.org requires: beautifulsoup4 chromedriver-binary (to be installed in python3 directory) PyYAML selenium ./credentials.yaml mu_username: <account name> mu_password: <password> md_username:<account name> md_password: <password> ''' from bs4 import BeautifulSou...
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
''' imports reading list from mangaupdates.com to mangadex.org requires: beautifulsoup4 chromedriver-binary (to be installed in python3 directory) PyYAML selenium ./credentials.yaml mu_username: <account name> mu_password: <password> md_username:<account name> md_password: <password> ''' from bs4 import BeautifulSou...
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
''' imports reading list from mangaupdates.com to mangadex.org requires: beautifulsoup4 chromedriver-binary (to be installed in python3 directory) PyYAML selenium ./credentials.yaml mu_username: <account name> mu_password: <password> md_username:<account name> md_password: <password> ''' from bs4 import BeautifulSou...
(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
// copyright Matthias Büchse, 2019 package main import ( "database/sql" "encoding/json" "errors" "fmt" "io" "log" "net/http" "sort" "strconv" "strings" "text/template" "time" "unicode" ) type Inter interface { Serialize(wr io.Writer, objects objectMap, obj object) error } func formatDate(layout string,...
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
// copyright Matthias Büchse, 2019 package main import ( "database/sql" "encoding/json" "errors" "fmt" "io" "log" "net/http" "sort" "strconv" "strings" "text/template" "time" "unicode" ) type Inter interface { Serialize(wr io.Writer, objects objectMap, obj object) error } func formatDate(layout string,...
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
// copyright Matthias Büchse, 2019 package main import ( "database/sql" "encoding/json" "errors" "fmt" "io" "log" "net/http" "sort" "strconv" "strings" "text/template" "time" "unicode" ) type Inter interface { Serialize(wr io.Writer, objects objectMap, obj object) error } func formatDate(layout string,...
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
// copyright Matthias Büchse, 2019 package main import ( "database/sql" "encoding/json" "errors" "fmt" "io" "log" "net/http" "sort" "strconv" "strings" "text/template" "time" "unicode" ) type Inter interface { Serialize(wr io.Writer, objects objectMap, obj object) error } func formatDate(layout string,...
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
import { Component, ViewChild, Injectable, Inject } from '@angular/core'; import {trigger, state, style, animate, transition } from '@angular/animations'; import { NavController, LoadingController, ToastController} from '@ionic/angular'; import { AudioService } from '../services/audio.service'; import {FormControl} ...
reset() { this.resetState(); this.currentFile = {}; this.displayFooter = 'inactive'; } }
{ if (this.onSeekState) { this.audioProvider.seekTo(event.target.value); this.play(); } else { this.audioProvider.seekTo(event.target.value); } }
identifier_body
tab2.page.ts
import { Component, ViewChild, Injectable, Inject } from '@angular/core'; import {trigger, state, style, animate, transition } from '@angular/animations'; import { NavController, LoadingController, ToastController} from '@ionic/angular'; import { AudioService } from '../services/audio.service'; import {FormControl} ...
} } } 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
import { Component, ViewChild, Injectable, Inject } from '@angular/core'; import {trigger, state, style, animate, transition } from '@angular/animations'; import { NavController, LoadingController, ToastController} from '@ionic/angular'; import { AudioService } from '../services/audio.service'; import {FormControl} f...
return this.store.dispatch({ type: LOADSTART, payload: { value: true, mediaInfo:file} }); } }); } pause() { this.audioProvider.pause(); this.currentFile.state = 1; } play() { if(this.state.info.playing){ this.pause(); } this.audioProvider.play(); this.currentF...
random_line_split
tab2.page.ts
import { Component, ViewChild, Injectable, Inject } from '@angular/core'; import {trigger, state, style, animate, transition } from '@angular/animations'; import { NavController, LoadingController, ToastController} from '@ionic/angular'; import { AudioService } from '../services/audio.service'; import {FormControl} ...
(action){ const message = JSON.parse(action).message; switch(message) { case 'music-controls-next': //this.musicControls.destroy(); //this.next(); break; case 'music-controls-previous': //this.musicControls.destroy(); ...
events
identifier_name
model.rs
#![allow(unused_unsafe)] use crate::com::*; use crate::consts::*; use crate::texture::*; use raw_window_handle::HasRawWindowHandle; use winapi::_core::f32::consts::PI; use winapi::_core::mem; use winapi::shared::basetsd::UINT16; use winapi::shared::minwindef::{FALSE, TRUE}; use winapi::shared::ntdef::HANDLE; use winapi...
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
#![allow(unused_unsafe)] use crate::com::*; use crate::consts::*; use crate::texture::*; use raw_window_handle::HasRawWindowHandle; use winapi::_core::f32::consts::PI; use winapi::_core::mem; use winapi::shared::basetsd::UINT16; use winapi::shared::minwindef::{FALSE, TRUE}; use winapi::shared::ntdef::HANDLE; use winapi...
(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
#![allow(unused_unsafe)] use crate::com::*; use crate::consts::*; use crate::texture::*; use raw_window_handle::HasRawWindowHandle; use winapi::_core::f32::consts::PI; use winapi::_core::mem; use winapi::shared::basetsd::UINT16; use winapi::shared::minwindef::{FALSE, TRUE}; use winapi::shared::ntdef::HANDLE; use winapi...
&mut fence_value, &mut frame_index, )?; self.fence_value = fence_value; self.frame_index = frame_index; Ok(()) } } // WAITING FOR THE FRAME TO COMPLETE BEFORE CONTINUING IS NOT BEST PRACTICE. // This is code implemented as such for simplicity. The D3D12HelloFra...
_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
#![allow(unused_unsafe)] use crate::com::*; use crate::consts::*; use crate::texture::*; use raw_window_handle::HasRawWindowHandle; use winapi::_core::f32::consts::PI; use winapi::_core::mem; use winapi::shared::basetsd::UINT16; use winapi::shared::minwindef::{FALSE, TRUE}; use winapi::shared::ntdef::HANDLE; use winapi...
// This is code implemented as such for simplicity. The D3D12HelloFrameBuffering // sample illustrates how to use fences for efficient resource usage and to // maximize GPU utilization. fn wait_for_previous_frame( swap_chain: &IDXGISwapChain3, command_queue: &ID3D12CommandQueue, fence: &ID3D12Fence, eve...
Ok(()) } } // WAITING FOR THE FRAME TO COMPLETE BEFORE CONTINUING IS NOT BEST PRACTICE.
random_line_split
art_tree.go
// Pacakge art provides a golang implementation of Adaptive Radix Trees package art import ( "bytes" _ "math" _ "os" ) type ArtTree struct { root *ArtNode size int64 } // Creates and returns a new Art Tree with a nil root and a size of 0. func NewArtTree() *ArtTree { return &ArtTree{root: nil, size: 0} } type...
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
// Pacakge art provides a golang implementation of Adaptive Radix Trees package art import ( "bytes" _ "math" _ "os" ) type ArtTree struct { root *ArtNode size int64 } // Creates and returns a new Art Tree with a nil root and a size of 0. func NewArtTree() *ArtTree { return &ArtTree{root: nil, size: 0} } type...
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
// Pacakge art provides a golang implementation of Adaptive Radix Trees package art import ( "bytes" _ "math" _ "os" ) type ArtTree struct { root *ArtNode size int64 } // Creates and returns a new Art Tree with a nil root and a size of 0. func NewArtTree() *ArtTree { return &ArtTree{root: nil, size: 0} } type...
// 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
// Pacakge art provides a golang implementation of Adaptive Radix Trees package art import ( "bytes" _ "math" _ "os" ) type ArtTree struct { root *ArtNode size int64 } // Creates and returns a new Art Tree with a nil root and a size of 0. func NewArtTree() *ArtTree { return &ArtTree{root: nil, size: 0} } type...
(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
//! Configures and runs the outbound proxy. //! //! The outound proxy is responsible for routing traffic from the local //! application to external network endpoints. #![deny(warnings, rust_2018_idioms)] use linkerd2_app_core::{ classify, config::Config, dns, drain, dst::DstAddr, errors, http_requ...
<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
//! Configures and runs the outbound proxy. //! //! The outound proxy is responsible for routing traffic from the local //! application to external network endpoints. #![deny(warnings, rust_2018_idioms)] use linkerd2_app_core::{ classify, config::Config, dns, drain, dst::DstAddr, errors, http_requ...
} impl transport::metrics::TransportLabels<proxy::server::Protocol> for TransportLabels { type Labels = transport::labels::Key; fn transport_labels(&self, proto: &proxy::server::Protocol) -> Self::Labels { transport::labels::Key::accept("outbound", proto.tls.peer_identity.as_ref()) } }
{ transport::labels::Key::connect("outbound", endpoint.identity.as_ref()) }
identifier_body
lib.rs
//! Configures and runs the outbound proxy. //! //! The outound proxy is responsible for routing traffic from the local //! application to external network endpoints. #![deny(warnings, rust_2018_idioms)] use linkerd2_app_core::{ classify, config::Config, dns, drain, dst::DstAddr, errors, http_requ...
// // 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
use reqwest::Client; use serde::{Deserialize, Serialize}; pub use url::Url; /// Data types to interract with the folder API. Check [FolderApi](folder::FolderApi) for the /// available actions. You can also check the [HTTP /// API](https://git.mdns.eu/nextcloud/passwords/wikis/Developers/Api/Folder-Api) pub mod folder;...
{ 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
use reqwest::Client; use serde::{Deserialize, Serialize}; pub use url::Url; /// Data types to interract with the folder API. Check [FolderApi](folder::FolderApi) for the /// available actions. You can also check the [HTTP /// API](https://git.mdns.eu/nextcloud/passwords/wikis/Developers/Api/Folder-Api) pub mod folder;...
/// Disconnect from the session pub async fn disconnect(self) -> Result<(), Error> { #[derive(Deserialize)] struct CloseSession { success: bool, } let s: CloseSession = self.passwords_get("1.0/session/close", ()).await.unwrap(); if !s.success { Er...
Ok((api, session_id)) }
random_line_split
infinite-article-origin.js
/* * jQuery throttle / debounce - v1.1 - 3/7/2010 * http://benalman.com/projects/jquery-throttle-debounce-plugin/ * * Copyright (c) 2010 "Cowboy" Ben Alman * Dual licensed under the MIT and GPL licenses. * http://benalman.com/about/license/ */ (function (b, c) { var $ = b.jQuery || b.Cowboy || (b.Cowboy = {}...
var targetNextNumber = targetNext.data('page-number'); webmd.infiniteScroll.showNext(target); var pageNumber = parseInt(targetNext.attr('id').slice(-1)); if (!webmd.useragent.ua.appview) { webmd.nativeAd.init({container: '#' + targ...
{ articleInfinite.opts.container.trigger('disableInfinite'); return; }
conditional_block
infinite-article-origin.js
/* * jQuery throttle / debounce - v1.1 - 3/7/2010 * http://benalman.com/projects/jquery-throttle-debounce-plugin/ * * Copyright (c) 2010 "Cowboy" Ben Alman * Dual licensed under the MIT and GPL licenses. * http://benalman.com/about/license/ */ (function (b, c) { var $ = b.jQuery || b.Cowboy || (b.Cowboy = {}...
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
/* * jQuery throttle / debounce - v1.1 - 3/7/2010 * http://benalman.com/projects/jquery-throttle-debounce-plugin/ * * Copyright (c) 2010 "Cowboy" Ben Alman * Dual licensed under the MIT and GPL licenses. * http://benalman.com/about/license/ */ (function (b, c) { var $ = b.jQuery || b.Cowboy || (b.Cowboy = {}...
var self = this; if (self.opts.beforeLoad !== null) { self.opts.beforeLoad(self.opts.content); } if (self.opts.afterLoad !== null) { self.opts.afterLoad($(self.opts.content)); } }, ...
* ---- IT'S CURRENTLY THE DEFAULT ---- */ nonAjaxCall: function () {
random_line_split
infinite-article-origin.js
/* * jQuery throttle / debounce - v1.1 - 3/7/2010 * http://benalman.com/projects/jquery-throttle-debounce-plugin/ * * Copyright (c) 2010 "Cowboy" Ben Alman * Dual licensed under the MIT and GPL licenses. * http://benalman.com/about/license/ */ (function (b, c) { var $ = b.jQuery || b.Cowboy || (b.Cowboy = {}...
() { 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
use shared::{ grid::{self as sg, Grid, GridTile, Coordinate}, input::read_stdin_lines }; use lazy_static::*; use regex::Regex; #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)] enum Tile { Clay, Sand, Spring, Water, WaterAtRest } struct Map { data: Vec<Vec<Tile>>, xstart: usize } im...
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
use shared::{ grid::{self as sg, Grid, GridTile, Coordinate}, input::read_stdin_lines }; use lazy_static::*; use regex::Regex; #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)] enum Tile { Clay, Sand, Spring, Water, WaterAtRest } struct Map { data: Vec<Vec<Tile>>, xstart: usize } im...
(&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
use shared::{ grid::{self as sg, Grid, GridTile, Coordinate}, input::read_stdin_lines }; use lazy_static::*; use regex::Regex; #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)] enum Tile { Clay, Sand, Spring, Water, WaterAtRest } struct Map { data: Vec<Vec<Tile>>, xstart: usize } im...
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
// Copyright 2020 The LUCI Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed...
func TestProjectLifeCycle(t *testing.T) { t.Parallel() Convey("Project can be created, updated, deleted", t, func() { ct := cvtesting.Test{} ctx, cancel := ct.SetUp() defer cancel() pmNotifier := prjmanager.NewNotifier(ct.TQDispatcher) runNotifier := runNotifierMock{} clMutator := changelist.NewMutato...
{ 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
// Copyright 2020 The LUCI Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed...
events, err := eventbox.List(ctx, recipient) So(err, ShouldBeNil) // Expect the following events: // +1 from NotifyCLsUpdated on cl43 and cl44, // +3*n from loop. So(events, ShouldHaveLength, 3*n+1) // Run `w` concurrent PMs. const w = 20 now := ct.Clock.Now() errs := make(errors.MultiError, w) ...
{ 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
// Copyright 2020 The LUCI Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed...
() common.RunIDs { r.m.Lock() out := r.updateConfig r.updateConfig = nil r.m.Unlock() sort.Sort(out) return out } func (r *runNotifierMock) popCancel() []cancellationRequest { r.m.Lock() out := r.cancel r.cancel = nil r.m.Unlock() sort.Slice(out, func(i, j int) bool { return out[i].id < out[j].id }) ret...
popUpdateConfig
identifier_name
manager_test.go
// Copyright 2020 The LUCI Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed...
key := datastore.MakeKey(ctx, prjmanager.ProjectKind, luciProject) ps := &prjmanager.ProjectStateOffload{Project: key} if err := datastore.Get(ctx, ps); err != nil { // ProjectStateOffload must exist if Project exists. panic(err) } plog := &prjmanager.ProjectLog{ Project: datastore.MakeKey(ctx, prjmanager....
random_line_split
point.js
// meant to be a wrapper around the graph functions with iterator // should be iterator and evaluatableIterator // // there needs to a way of caching the ptr subnodes // var pointLookup = {} function point(options){ this.nodePtr = copyArray(ptr); this.nodePtr.pop();this.nodePtr.pop(); this.ptr = options.ptr; t...
(ptr) { this.descendants = []; graph.prototype.recurseItems(selectInternodeDescendants.prototype.getNextChild()); } selectInternodeDescendants.prototype.getNextChild = function(ptr, obj) { for (var i = obj.index; i >=0 ;i--) { var link = obj[i]; //if (link.parents[0].length || link.children[0].length) thi...
selectInternodeDescendants
identifier_name
point.js
// meant to be a wrapper around the graph functions with iterator // should be iterator and evaluatableIterator // // there needs to a way of caching the ptr subnodes // var pointLookup = {} function point(options){ this.nodePtr = copyArray(ptr); this.nodePtr.pop();this.nodePtr.pop(); this.ptr = options.ptr; t...
setNextContext.prototype = { "setNextContext":function() { // search for element and set flag this.recurse = function(point) { for (var i = 0; i < point.children.length; i ++) { var o = point.children[i]; if (!o.isProgram) { o.setContext();// = true; }else this(o); } } this.recurse(th...
{ }
identifier_body
point.js
// meant to be a wrapper around the graph functions with iterator // should be iterator and evaluatableIterator // // there needs to a way of caching the ptr subnodes // var pointLookup = {} function point(options){ this.nodePtr = copyArray(ptr); this.nodePtr.pop();this.nodePtr.pop(); this.ptr = options.ptr; t...
} function getNextLinks(ptr, priorPtr) { this.ptr = ptr; var o = getObject (this.ptr, graphLookup); var cap = []; var a = o.children.concat(o.parents); for (var i = 0; i < o.length; i++) { if (a[i] != ptr) { var o = getObject(a[i], graphLookup); var ctop = o.gfx.bottom + o.gfx.height; cap.pus...
{ 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
// meant to be a wrapper around the graph functions with iterator // should be iterator and evaluatableIterator // // there needs to a way of caching the ptr subnodes // var pointLookup = {} function point(options){ this.nodePtr = copyArray(ptr); this.nodePtr.pop();this.nodePtr.pop(); this.ptr = options.ptr; th...
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
//! The solana-program-test provides a BanksClient-based test framework BPF programs use chrono_humanize::{Accuracy, HumanTime, Tense}; use log::*; use solana_banks_client::start_client; use solana_banks_server::banks_server::start_local_server; use solana_program::{ account_info::AccountInfo, entrypoint::ProgramR...
(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
//! The solana-program-test provides a BanksClient-based test framework BPF programs use chrono_humanize::{Accuracy, HumanTime, Tense}; use log::*; use solana_banks_client::start_client; use solana_banks_server::banks_server::start_local_server; use solana_program::{ account_info::AccountInfo, entrypoint::ProgramR...
/// Override default BPF program selection pub fn prefer_bpf(&mut self, prefer_bpf: bool) { self.prefer_bpf = prefer_bpf; } /// Override the BPF compute budget pub fn set_bpf_compute_max_units(&mut self, bpf_compute_max_units: u64) { self.bpf_compute_max_units = Some(bpf_compute_m...
{ let mut me = Self::default(); me.add_program(program_name, program_id, process_instruction); me }
identifier_body
lib.rs
//! The solana-program-test provides a BanksClient-based test framework BPF programs use chrono_humanize::{Accuracy, HumanTime, Tense}; use log::*; use solana_banks_client::start_client; use solana_banks_server::banks_server::start_local_server; use solana_program::{ account_info::AccountInfo, entrypoint::ProgramR...
if (program_file.is_some() && self.prefer_bpf) || process_instruction.is_none() { let program_file = program_file.unwrap_or_else(|| { panic!( "Program file data not available for {} ({})", program_name, program_id ); ...
}
random_line_split
utils.rs
// Copyright (c) 2011 Jan Kokemüller // Copyright (c) 2020 Sebastian Dröge <sebastian@centricular.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including wit...
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
// Copyright (c) 2011 Jan Kokemüller // Copyright (c) 2020 Sebastian Dröge <sebastian@centricular.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including wit...
mut self) -> Option<Signal<A>> { if self.size < self.seed.data.len() { // Generate a smaller vector by removing size elements let xs1 = if self.tried_one_channel { Vec::from(&self.seed.data[..self.size]) } else { self.se...
xt(&
identifier_name
utils.rs
// Copyright (c) 2011 Jan Kokemüller // Copyright (c) 2020 Sebastian Dröge <sebastian@centricular.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including wit...
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
// Copyright (c) 2011 Jan Kokemüller // Copyright (c) 2020 Sebastian Dröge <sebastian@centricular.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including wit...
lse { 1 }; } else { self.size *= 2; } Some(Signal { data: xs1, channels: if self.tried_one_channel { self.seed.channels } e...
self.seed.channels as usize } e
conditional_block
libstore-impl.go
package libstore import ( "P2-f12/official/cacherpc" "P2-f12/official/lsplog" "P2-f12/official/storageproto" "fmt" "net/rpc" "os" "sort" "strings" "time" ) const ( GETRPCCLI = iota WANTLEASE CACHEGET CACHEPUT CACHEDEL RETRY_INTERVAL = time.Second RETRY_LIMIT = 5 QUERY_CACHE_INTERVAL =...
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
package libstore import ( "P2-f12/official/cacherpc" "P2-f12/official/lsplog" "P2-f12/official/storageproto" "fmt" "net/rpc" "os" "sort" "strings" "time" ) const ( GETRPCCLI = iota WANTLEASE CACHEGET CACHEPUT CACHEDEL RETRY_INTERVAL = time.Second RETRY_LIMIT = 5 QUERY_CACHE_INTERVAL =...
(args *storageproto.RevokeLeaseArgs, reply *storageproto.RevokeLeaseReply) error { ls.syncopchan <- &syncop{CACHEDEL, args.Key, nil} <-ls.successreplychan reply.Status = storageproto.OK return nil } // Implement sorting interface for storageproto.Node type NodeList []storageproto.Node func (nodes NodeList) Len() ...
RevokeLease
identifier_name
libstore-impl.go
package libstore import ( "P2-f12/official/cacherpc" "P2-f12/official/lsplog" "P2-f12/official/storageproto" "fmt" "net/rpc" "os" "sort" "strings" "time" ) const ( GETRPCCLI = iota WANTLEASE CACHEGET CACHEPUT CACHEDEL RETRY_INTERVAL = time.Second RETRY_LIMIT = 5 QUERY_CACHE_INTERVAL =...
// Revokes the lease when the time duration expires func (ls *Libstore) expireLease(key string, duration time.Duration) { <-time.After(duration) ls.syncopchan <- &syncop{CACHEDEL, key, nil} <-ls.successreplychan } // Revokes the lease corresponding to the key in the arguments when activated as a callback func (ls...
{ 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
package libstore import ( "P2-f12/official/cacherpc" "P2-f12/official/lsplog" "P2-f12/official/storageproto" "fmt" "net/rpc" "os" "sort" "strings" "time" ) const ( GETRPCCLI = iota WANTLEASE CACHEGET CACHEPUT CACHEDEL RETRY_INTERVAL = time.Second RETRY_LIMIT = 5 QUERY_CACHE_INTERVAL =...
if reply.Status != storageproto.OK { return lsplog.MakeErr("RemoveFromList failed: Storage error") } return nil } // Append an element to a list func (ls *Libstore) iAppendToList(key, newitem string) error { args := &storageproto.PutArgs{key, newitem} var reply storageproto.PutReply cli, err := ls.getServer(...
{ return err }
conditional_block
router.rs
use anyhow::{bail, Result}; use indexmap::indexmap; use serde::Deserialize; use serde_json::json; use turbo_tasks::{ primitives::{JsonValueVc, StringsVc}, CompletionVc, CompletionsVc, Value, }; use turbo_tasks_fs::{ json::parse_json_rope_with_source_context, to_sys_path, File, FileSystemPathVc, }; use turbo...
( execution_context: ExecutionContextVc, request: RouterRequestVc, next_config: NextConfigVc, server_addr: ServerAddrVc, routes_changed: CompletionVc, ) -> Result<RouterResultVc> { let ExecutionContext { project_path, chunking_context, env, } = *execution_context.awai...
route_internal
identifier_name
router.rs
use anyhow::{bail, Result}; use indexmap::indexmap; use serde::Deserialize; use serde_json::json; use turbo_tasks::{ primitives::{JsonValueVc, StringsVc}, CompletionVc, CompletionsVc, Value, }; use turbo_tasks_fs::{ json::parse_json_rope_with_source_context, to_sys_path, File, FileSystemPathVc, }; use turbo...
AssetIdentVc::from_path(project_path), context, chunking_context.with_layer("router"), None, vec![ JsonValueVc::cell(request), JsonValueVc::cell(dir.to_string_lossy().into()), ], CompletionsVc::all(vec![next_config_changed, routes_changed])...
}; let result = evaluate( router_asset, project_path, env,
random_line_split
minimize.rs
use std::cmp::max; use std::cmp::Ordering; use std::collections::hash_map::Entry; use std::collections::HashMap; use std::collections::HashSet; use std::marker::PhantomData; use anyhow::Result; use binary_heap_plus::BinaryHeap; use stable_bst::TreeMap; use crate::algorithms::encode::EncodeType; use crate::algorithms:...
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
use std::cmp::max; use std::cmp::Ordering; use std::collections::hash_map::Entry; use std::collections::HashMap; use std::collections::HashSet; use std::marker::PhantomData; use anyhow::Result; use binary_heap_plus::BinaryHeap; use stable_bst::TreeMap; use crate::algorithms::encode::EncodeType; use crate::algorithms:...
<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
use std::cmp::max; use std::cmp::Ordering; use std::collections::hash_map::Entry; use std::collections::HashMap; use std::collections::HashSet; use std::marker::PhantomData; use anyhow::Result; use binary_heap_plus::BinaryHeap; use stable_bst::TreeMap; use crate::algorithms::encode::EncodeType; use crate::algorithms:...
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
package dt import "encoding/json" // StateKey is a reserved key in the state of a plugin that tracks which state // the plugin is currently in for each user. const StateKey string = "__state" // StateKeyEntered keeps track of whether the current state has already been // "entered", which determines whether the OnEnt...
(in *Msg) { sm.state = 0 sm.stateEntered = false sm.plugin.SetMemory(in, StateKey, 0) sm.plugin.SetMemory(in, stateEnteredKey, false) sm.resetFn(in) } // SetState jumps from one state to another by its label. It will safely jump // forward but NO safety checks are performed on backward jumps. It's therefore // up...
Reset
identifier_name
state_machine.go
package dt import "encoding/json" // StateKey is a reserved key in the state of a plugin that tracks which state // the plugin is currently in for each user. const StateKey string = "__state" // StateKeyEntered keeps track of whether the current state has already been // "entered", which determines whether the OnEnt...
// If we're in a state before the desired state, go forward only as far // as we're allowed by the Complete guards. for s := sm.state; s < desiredState; s++ { ok, _ := sm.Handlers[s].Complete(in) if !ok { sm.state = s sm.stateEntered = false sm.plugin.SetMemory(in, StateKey, s) sm.plugin.SetMemory(in...
random_line_split
state_machine.go
package dt import "encoding/json" // StateKey is a reserved key in the state of a plugin that tracks which state // the plugin is currently in for each user. const StateKey string = "__state" // StateKeyEntered keeps track of whether the current state has already been // "entered", which determines whether the OnEnt...
// setEntered is used internally to set a state as having been entered both in // memory and persisted to the database. This ensures that a stateMachine does // not run a state's OnEntry function twice. func (sm *StateMachine) setEntered(in *Msg) { sm.stateEntered = true sm.plugin.SetMemory(in, stateEnteredKey, tru...
{ // 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
package dt import "encoding/json" // StateKey is a reserved key in the state of a plugin that tracks which state // the plugin is currently in for each user. const StateKey string = "__state" // StateKeyEntered keeps track of whether the current state has already been // "entered", which determines whether the OnEnt...
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
// Autor: (c) St. Schmidt (Kontakt: St.Schmidt@online.de) // Datum: 04.02.2019-07.02.2019; letzte Änderung: 06.11.2020 // --> Damit entspricht der Stand von gfx2 dem von gfx vom 06.11.2020 // Zweck: TCP/IP-Server, der ein gfx-Grafikfenster verwaltet // - Grafik- und Soundausgabe und Eingabe per Tastat...
// 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
// Diagnostics engine use super::{Span, SrcMgr}; use std::cell::RefCell; use std::cmp; use std::fmt; use std::rc::Rc; use colored::{Color, Colorize}; /// Severity of the diagnostic message. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Severity { Remark, Info, Warning, Error, Fatal, } im...
/// Clear exsting diagnostics pub fn clear(&self) { let mut m = self.mutable.borrow_mut(); m.diagnostics.clear(); } /// Check if there is any fatal error. pub fn has_fatal(&self) -> bool { let m = self.mutable.borrow(); m.diagnostics .iter() ...
{ self.report(Diagnostic::new(Severity::Fatal, msg.into(), span)); std::panic::panic_any(Severity::Fatal); }
identifier_body
diag.rs
// Diagnostics engine use super::{Span, SrcMgr}; use std::cell::RefCell; use std::cmp; use std::fmt; use std::rc::Rc; use colored::{Color, Colorize}; /// Severity of the diagnostic message. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Severity { Remark, Info, Warning, Error, Fatal, } im...
} } // 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
// Diagnostics engine use super::{Span, SrcMgr}; use std::cell::RefCell; use std::cmp; use std::fmt; use std::rc::Rc; use colored::{Color, Colorize}; /// Severity of the diagnostic message. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Severity { Remark, Info, Warning, Error, Fatal, } im...
(&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
// Copyright 2016 The android_logger Developers // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except a...
/// 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
// Copyright 2016 The android_logger Developers // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except a...
(_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
// Copyright 2016 The android_logger Developers // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except a...
} /// Copy `len` bytes from `index` position to starting position. fn copy_bytes_to_start(&mut self, index: usize, len: usize) { let src = unsafe { self.buffer.as_ptr().offset(index as isize) }; let dst = self.buffer.as_mut_ptr(); unsafe { ptr::copy(src, dst, len) }; } } impl<'...
*unsafe { self.buffer.get_unchecked_mut(len) } = last_byte;
random_line_split
lib.rs
// Copyright 2016 The android_logger Developers // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except a...
}); // update last \n index if let Some(newline) = last_newline { self.last_newline_index = len + newline; } // calculate how many bytes were written let written_len = if new_len <= LOGGING_MSG_MAX_LEN { // if...
{ acc }
conditional_block
dss.go
/* Package dss implements variants of a DAG-structured stack (DSS). It is used for GLR-parsing and for substring parsing. A DSS is suitable for parsing with ambiguous grammars, so the parser can execute a breadth-first (quasi-)parallel shift and/or reduce operation in inadequate (ambiguous) parse states. Each parser (...
if node.isInverseJoin() { T().Debugf("is join: %v", node) maydelete = true node.pathcnt-- } else if haveDeleted && node.successorCount() > 0 { T().Debugf("is or has been fork: %v", node) maydelete = false } else { maydelete = true node.pathcnt-- } if i == 0 { // when popped every node: ev...
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
/* Package dss implements variants of a DAG-structured stack (DSS). It is used for GLR-parsing and for substring parsing. A DSS is suitable for parsing with ambiguous grammars, so the parser can execute a breadth-first (quasi-)parallel shift and/or reduce operation in inadequate (ambiguous) parse states. Each parser (...
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
/* Package dss implements variants of a DAG-structured stack (DSS). It is used for GLR-parsing and for substring parsing. A DSS is suitable for parsing with ambiguous grammars, so the parser can execute a breadth-first (quasi-)parallel shift and/or reduce operation in inadequate (ambiguous) parse states. Each parser (...
} return nil } type pseudo struct { name string } func pseudosym(name string) lr.Symbol { return &pseudo{name: name} } func (sy *pseudo) String() string { return sy.name } func (sy *pseudo) IsTerminal() bool { return true } func (sy *pseudo) Token() int { return 0 } func (sy *pseudo) GetID() int { return...
{ return n }
conditional_block
dss.go
/* Package dss implements variants of a DAG-structured stack (DSS). It is used for GLR-parsing and for substring parsing. A DSS is suitable for parsing with ambiguous grammars, so the parser can execute a breadth-first (quasi-)parallel shift and/or reduce operation in inadequate (ambiguous) parse states. Each parser (...
() 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