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
utils.py
by `source_iter` and returns other objects. `filter_func` is what will be applied to the SOURCE object to decide if it will be returned. """ self.source_iter = iter(source_iter) self.casting_func = casting_func self.filter_func = filter_func def __iter__(self): ...
"Sets an item using a case-insensitive key," if key.lower() not in self: self.__ordered_keys.append(str(key)) super(OrderedCaselessDict, self).__setitem__(key.lower(), value) def __delitem__(self, key): "Remove item with specified key." del(self.__ordered_keys[se...
def __getitem__(self, key): "Gets an item using a case-insensitive key." return super(OrderedCaselessDict, self).__getitem__(key.lower()) def __setitem__(self, key, value):
random_line_split
utils.py
`source_iter` and returns other objects. `filter_func` is what will be applied to the SOURCE object to decide if it will be returned. """ self.source_iter = iter(source_iter) self.casting_func = casting_func self.filter_func = filter_func def __iter__(self): ...
(self, other): """ updates (and overwrites) key/value pairs: k = { 'a':'A', 'b':'B', 'c':'C'} q = { 'c':'C', 'd':'D', 'f':'F'} k.update(q) {'a': 'A', 'c': 'C', 'b': 'B', 'd': 'D', 'f': 'F'} """ for key, val in other.items(): if key.lower() not ...
update
identifier_name
utils.py
edCaselessDict, self).__init__() self.__ordered_keys = [] if other is not None: if isinstance(other, dict): for key, val in other.items(): if key.lower() not in self: self.__ordered_keys.append(str(key)) super(Or...
return False
conditional_block
utils.py
by `source_iter` and returns other objects. `filter_func` is what will be applied to the SOURCE object to decide if it will be returned. """ self.source_iter = iter(source_iter) self.casting_func = casting_func self.filter_func = filter_func def __iter__(self): ...
def __repr__(self): "Returns a representation of self's ordered keys." return "%s([%s])" \ % (self.__class__.__name__, ', \ '.join(["(%r, %r)" % item for item in self.iteritems()])) def __str__(self): "Returns a string representation of self." ...
"Returns an iterator over self's ordered keys." return self.iterkeys()
identifier_body
index.js
common.ajaxPost({ method : 'firm_default', firmId : pub.firmId },function(d){ switch( +d.statusCode ){ case 100000 : pub.apiHandle.firm_default.apiData( d.data ); break; case 100400 : common.clearData(); break; case 100901 : common.dialog.init({ btns : [{ klass : 'dialog...
dex_inner").empty(); data.mainPageGoodsDetails.length != 0 && me.apiDataDeal( data.mainPageGoodsDetails ); common.isWeiXin() && (function(){ common.weixin.config( location.href.split('#')[0] ); common.weixin.share( d.data.customShare ); }()); } }; pub.get_weixin_code = function(){ ...
rl ? d[i].linkUrl : 'javascript:void(0)' ) + '"><img src="' + d[i].adLogo + '" /></a></div>' } return html; }); $(".in
conditional_block
index.js
}, apiData : function( d ){ var json = {}, me = this, data = d.data; if( !common.timestamp.getKey() && data.adInfoList.length != 0 && data.mainPageGoodsDetails.length != 0 ){ json.timestamp = Date.now() + 3 * 60 * 1000; json.con = d; common.timestamp.setItem( common.JSONStr( jso...
!pub.accountRelatived && pub.logined && pub.accountRelative.resolve(); // 关联 }()); }());
random_line_split
main.rs
= self.offset * 10 + c; } fn add_arg_length(&mut self, c: usize) { self.length = self.length * 10 + c; } } fn main() { let mut host = String::from("0.0.0.0:8888"); //let mut host = String::from("[::]:8888"); let mut dictdir = String::from("/usr/share/stardict/dic"); let dict; { ...
{ //html js css page etc. if let Ok(fname) = str::from_utf8(&surl.word) { let mut pfile = path::PathBuf::from(dictdir); pfile.push(fname); if let Ok(mut f) = fs::File::open(pfile) { if f.read_to_end(&mut ...
conditional_block
main.rs
.directories.len()); for it in &self.directories { items.push(&it.ifo); } items } /// List the following neighbor words of `word`, from `off`. /// If `off` is a negative number, list from before `-off`. pub fn neighbors(&self, word: &[u8], off: i32) -> WordMergeIter<d...
/// Search from all dictionaries. using the specified regular expression. /// to match the beginning of a word, use `^`, the ending of a word, use `$`. pub fn search<'a>(&'a self, reg: &'a Regex) -> WordMergeIter<dictionary::IdxIter> { let mut wordit = Vec::with_capacity(2 * self.directories.len())...
{ let mut wordit = Vec::with_capacity(2 * self.directories.len()); let mut cur = Vec::with_capacity(2 * self.directories.len()); for d in self.directories.iter() { let mut x = d.neighbors(word, off); let mut s = d.neighbors_syn(word, off); cur.push(x.next()); ...
identifier_body
main.rs
<T: Iterator<Item = Vec<u8>>> { wordit: Vec<T>, cur: Vec<Option<Vec<u8>>>, } impl<'a, T: Iterator<Item = Vec<u8>>> Iterator for WordMergeIter<T> { type Item = Vec<u8>; fn next(&mut self) -> Option<Self::Item> { let l = self.cur.len(); if l == 0 { return None; } ...
WordMergeIter
identifier_name
main.rs
println!("parameter: [-d] [-h host:port] [-r dict-root-dir]"); return; } } if a[0] == b'-' { pendarg = a[1]; } } //println!("get arg host={}, daemon={}", host, daemon); //if daemon { //} dic...
if surl.path[0] == b'n' { stream.write(b"text/plain")?;
random_line_split
jsontest.js
015", "Time": "3-4.30pm", "Location": "Decorative Arts & History", "Description": " Can you follow the trail and test your knowledge to find the golden egg? Complete the trail to receive an egg-cellent edible reward!", "Booking Information": "No booking required.", "Format": "Family Event", "Aud...
"Event": "Seminar: Method and Form", "Start Date": "25th April 2015", "Finish Date": "25th April 2015", "Time": "2-4.pm", "Location": "Decorative Arts & History", "Description": "Marking Year of Irish Design 2015, and in partnership with the Dublin Decorative & Fine Arts Society, 'Method and For...
},{
random_line_split
jsontest.js
Audience": "All ages" },{ "Event": "70th Anniversary of the end of World War Two", "Start Date": "6th June 2015", "Finish Date": "6th June 2015", "Time": "2-4.30pm", "Location": "Decorative Arts & History", "Description": "Come along and see uniforms and equipment used by the Allied (American...
es(obj, k
identifier_name
jsontest.js
ative Arts & History", "Description": "Come along and see uniforms and equipment used by the Allied (American, British, French, Soviet) and Axis (German, Italian) Forces during the Second World War. This is an interactive way of learning about this conflict which ended 70 years ago. Presented by historical re-enact...
ar objects = []; for (var i in obj) { if (!obj.hasOwnProperty(i)) continue; if (typeof obj[i] == 'object') { objects = objects.concat(getValues(obj[i], key)); } else if (i == key) { objects.push(obj[i]); } } return objects; } var j
identifier_body
Python_SQL_Project_CodeBase-DA.py
="Sets the SQL Server DB Username", type=str) argParser.add_argument("-p", "--DBUserPassword", dest="dbuserpassword", \ action='store', help="Sets the SQL Server DB User Password", type=str) argParser.add_argument("-t", "--UseTrustedConnection", dest="trustedmode", \ ...
def compareDBSurveyStructureToPersistenceFile(surveyStructResults:pd.DataFrame, persistenceFilePath: str) -> bool: same_file = False try: unpickled_persistanceFileDF = pd.read_csv(persistenceFilePath) if(surveyStructResults.equals(unpickled_persistanceFileDF) == True): sa...
success = True if(os.access(os.path.dirname(persistenceFilePath), os.W_OK) == False): success = False return success
identifier_body
Python_SQL_Project_CodeBase-DA.py
sn, "dbserver" : argParsingResults.dbserver, "dbname" : argParsingResults.dbname, "dbusername" : argParsingResults.dbusername, "dbuserpassword" : dbpassword, "trustedmode" : argParsingResults.trustedmode, ...
#TODO refreshViewInDB(connector, getAllSurveyDataQuery(connector), cliArguments['viewname']) else:
random_line_split
Python_SQL_Project_CodeBase-DA.py
fuscator.obfuscate(argParsingResults.dbuserpassword) else: if(argParsingResults.dbusername is not None): raise Exception("You are using the TrustedConnection Mode yet providing DB user name: this will be disregarded in TrustedConnection") retParametersDictionary...
try: connector = mssql.MSSQL_DBConnector(DSN = cliArguments["dsn"], dbserver = cliArguments["dbserver"], \ dbname = cliArguments["dbname"], dbusername = cliArguments["dbusername"], \ dbpassword = cliArguments["dbuserpassword"], trustedmode = cliArguments["trustedmode"], \ ...
conditional_block
Python_SQL_Project_CodeBase-DA.py
="Sets the SQL Server DB Username", type=str) argParser.add_argument("-p", "--DBUserPassword", dest="dbuserpassword", \ action='store', help="Sets the SQL Server DB User Password", type=str) argParser.add_argument("-t", "--UseTrustedConnection", dest="trustedmode", \ ...
(persistenceFilePath: str)-> bool: success = True if(os.access(os.path.dirname(persistenceFilePath), os.W_OK) == False): success = False return success def compareDBSurveyStructureToPersistenceFile(surveyStructResults:pd.DataFrame, persistenceFilePath: str) -> bool: same_file = False ...
isPersistenceFileDirectoryWritable
identifier_name
versioned_object_tracker.go
name. Get(gvr schema.GroupVersionResource, ns, name string) (runtime.Object, error) // Create adds an object to the tracker in the specified namespace. Create(gvr schema.GroupVersionResource, obj runtime.Object, ns string) error // Update updates an existing object in the tracker in the specified namespace. Upd...
t.lock.RLock() defer t.lock.RUnlock() objs, ok := t.objects[gvr] if !ok { return list, nil } matchingObjs, err := filterByNamespace(objs, ns) if err != nil { return nil, err } if err := meta.SetList(list, matchingObjs); err != nil { return nil, err } return list.DeepCopyObject(), nil } func (t *tr...
{ // Heuristic for list kind: original kind + List suffix. Might // not always be true but this tracker has a pretty limited // understanding of the actual API model. listGVK := gvk listGVK.Kind = listGVK.Kind + "List" // GVK does have the concept of "internal version". The scheme recognizes // the runtime.APIVe...
identifier_body
versioned_object_tracker.go
and name. Get(gvr schema.GroupVersionResource, ns, name string) (runtime.Object, error) // Create adds an object to the tracker in the specified namespace. Create(gvr schema.GroupVersionResource, obj runtime.Object, ns string) error // Update updates an existing object in the tracker in the specified namespace. ...
} if err := meta.SetList(list, matchingObjs); err != nil { return nil, err } return list.DeepCopyObject(), nil } func (t *tracker) Watch(gvr schema.GroupVersionResource, ns string) (watch.Interface, error) { t.lock.Lock() defer t.lock.Unlock() fakewatcher := watch.NewRaceFreeFake() if _, exists := t.watche...
random_line_split
versioned_object_tracker.go
and name. Get(gvr schema.GroupVersionResource, ns, name string) (runtime.Object, error) // Create adds an object to the tracker in the specified namespace. Create(gvr schema.GroupVersionResource, obj runtime.Object, ns string) error // Update updates an existing object in the tracker in the specified namespace. ...
(gvr schema.GroupVersionResource, ns, name string) (runtime.Object, error) { errNotFound := errors.NewNotFound(gvr.GroupResource(), name) t.lock.RLock() defer t.lock.RUnlock() objs, ok := t.objects[gvr] if !ok { return nil, errNotFound } matchingObj, ok := objs[types.NamespacedName{Namespace: ns, Name: name...
Get
identifier_name
versioned_object_tracker.go
) (watch.Interface, error) GetResourceVersion() uint64 } // ObjectScheme abstracts the implementation of common operations on objects. type ObjectScheme interface { runtime.ObjectCreater runtime.ObjectTyper } type tracker struct { scheme ObjectScheme decoder runtime.Decoder lock sync.RWMutex objects map[s...
{ return errs[0] }
conditional_block
lib.rs
by bindgen, generating the C++ bindings. /// Any C++ parsing errors, etc. would be reported this way. Bindgen(()), /// Any problem parsing the Rust file. Parsing(syn::Error), /// No `include_cpp!` macro could be found. NoAutoCxxInc, /// The include directories specified were incorreect. ...
// instead of requiring callers always to set AUTOCXX_INC. // On Windows, the canonical path begins with a UNC prefix that cannot be passed to // the MSVC compiler, so dunce::canonicalize() is used instead of std::fs::canonicalize() // See: // * https://github.com/dtolnay/cxx/pu...
let inc_dirs = std::env::split_paths(&inc_dirs); // TODO consider if we can or should look up the include path automatically
random_line_split
lib.rs
), /// No `include_cpp!` macro could be found. NoAutoCxxInc, /// The include directories specified were incorreect. CouldNotCanoncalizeIncludeDir(PathBuf), /// Some error occcurred in converting the bindgen-style /// bindings to safe cxx bindings. Conversion(conversion::ConvertError), //...
{ let full_header = self.build_header(); let full_header = format!("{}\n\n{}", KNOWN_TYPES.get_prelude(), full_header,); builder = builder.header_contents("example.hpp", &full_header); builder }
identifier_body
lib.rs
_database.add_to_allowlist("make_string".to_string()); } if !unsafe_found { return Err(syn::Error::new( input.span(), "the unsafe keyword must be specified within each include_cpp! block", )); } Ok(IncludeCpp { inclusio...
include_dirs
identifier_name
hwacha.py
def __init__(self, scalars): self.scalars = scalars def visit_Constant(self, node):
def get_scalars_in_body(node): scalars = set() visitor = ScalarFinder(scalars) for stmt in node.body: visitor.visit(stmt) return scalars number_dict = { "1": "one", "2": "two", "3": "three", "4": "four", "5": "five", "6": "six", "7": "seven", "8": "eight", ...
self.scalars.add(node.value)
identifier_body
hwacha.py
def __init__(self, scalars): self.scalars = scalars def visit_Constant(self, node): self.scalars.add(node.value) def get_scalars_in_body(node): scalars = set() visitor = ScalarFinder(scalars) for stmt in node.body: visitor.visit(stmt) return scalars number_dict = { "1...
(ast.NodeTransformer): def __init__(self, type_map, defns): self.type_map = type_map self.defns = defns def visit_For(self, node): if node.pragma == "ivdep": block = [] loopvar = node.incr.arg size = node.test.right scalars = get_scalars_i...
HwachaVectorize
identifier_name
hwacha.py
class ScalarFinder(ast.NodeVisitor): def __init__(self, scalars): self.scalars = scalars def visit_Constant(self, node): self.scalars.add(node.value) def get_scalars_in_body(node): scalars = set() visitor = ScalarFinder(scalars) for stmt in node.body: visitor.visit(stmt) ...
"""
random_line_split
hwacha.py
def __init__(self, scalars): self.scalars = scalars def visit_Constant(self, node): self.scalars.add(node.value) def get_scalars_in_body(node): scalars = set() visitor = ScalarFinder(scalars) for stmt in node.body: visitor.visit(stmt) return scalars number_dict = { "1...
for index, scalar in enumerate(scalars): reg = "vs{}".format(index) scalar_register_map[scalar] = reg self.type_map[reg] = get_ctype(scalar) body = [] block.append(StringTemplate(hwacha_configure_block.format(SIZE=size))) ...
ref_register_map[str(ref)] = (ref, "va{}".format(index))
conditional_block
lib.rs
, State}, parse::{ParsedJob, ParsedLine, ParsedTask}, }; use alloc::{borrow::ToOwned, format, string::String, sync::Arc, vec::Vec}; use app_io::{println, IoStreams}; use core::fmt::Write; use hashbrown::HashMap; use job::Job; use log::{error, warn}; use noline::{builder::EditorBuilder, sync::embedded::IO as Io}; us...
.map_err(Error::SpawnFailed)? .argument(args.into_iter().map(ToOwned::to_owned).collect::<Vec<_>>()) .block() .spawn() .unwrap(); let task_ref = task.clone(); let
{ let namespace_dir = task::get_my_current_task() .map(|t| t.get_namespace().dir().clone()) .expect("couldn't get namespace dir"); let crate_name = format!("{cmd}-"); let mut matching_files = namespace_dir .get_files_starting_with(&crate_name) .in...
identifier_body
lib.rs
, State}, parse::{ParsedJob, ParsedLine, ParsedTask}, }; use alloc::{borrow::ToOwned, format, string::String, sync::Arc, vec::Vec}; use app_io::{println, IoStreams}; use core::fmt::Write; use hashbrown::HashMap; use job::Job; use log::{error, warn}; use noline::{builder::EditorBuilder, sync::embedded::IO as Io}; us...
while let Some(ParsedTask { command, args }) = task { if iter.peek().is_none() { if let Some(result) = self.execute_builtin(command, &args) { self.jobs.lock().remove(&job_id); return result.map(|_| None); } else { ...
} drop(jobs);
random_line_split
lib.rs
, State}, parse::{ParsedJob, ParsedLine, ParsedTask}, }; use alloc::{borrow::ToOwned, format, string::String, sync::Arc, vec::Vec}; use app_io::{println, IoStreams}; use core::fmt::Write; use hashbrown::HashMap; use job::Job; use log::{error, warn}; use noline::{builder::EditorBuilder, sync::embedded::IO as Io}; us...
(&mut self, line: &str) -> Result<()> { let parsed_line = ParsedLine::from(line); if parsed_line.is_empty() { return Ok(()); } // TODO: Use line editor history. self.history.push(line.to_owned()); for (job_str, job) in parsed_line.background { i...
execute_line
identifier_name
leaflet.js
config.map.topojson.parser(geom); var found = vm._data.filter((o) => o[vm._config.id] == geom.id)[0]; if (found) { geom.properties[vm._config.fill] = found[vm._config.fill]; } vm._nodes.push(geom); }); } // vm._config.map.min = vm._minMax[0]; // vm._config.ma...
{ var value = layer.feature.properties[vm._config.fill]; if (!value) { // Remove polygons without data /** @todo validate what to do with NA's */ d3.select(layer._path).remove(); } else { var fillColor = vm._scales.color(value); layer.setStyle({ fillC...
identifier_body
leaflet.js
json.objects[obj].geometries.forEach(function (geom) { geom.id = vm._config.map.topojson.parser(geom); var found = vm._data.filter((o) => o[vm._config.id] == geom.id)[0]; if (found) { geom.properties[vm._config.fill] = found[vm._config.fill]; } vm._nodes.pus...
handleLayer
identifier_name
leaflet.js
colors; } return vm; };
return vm; }; // ------------------------------- // Triggered by chart.js; Leaflet.data = function (data) { var vm = this; vm._topojson = data[1] ? data[1] : false; //Topojson data = data[0]; //User data if (vm._config.data.filter) { data = data.filter(vm._config.data.filter); } ...
Leaflet.colorLegend = function (legendTitle) { var vm = this; vm._config.legendTitle = legendTitle;
random_line_split
leaflet.js
colors; } return vm; }; Leaflet.colorLegend = function (legendTitle) { var vm = this; vm._config.legendTitle = legendTitle; return vm; }; // ------------------------------- // Triggered by chart.js; Leaflet.data = function (data) { var vm = this; vm._topojson = data[1] ? data[...
}, }); var LatLng = { lat: 25.5629994, lon: -100.6405644, }; if ( vm._config.map.topojson.center && vm._config.map.topojson.center.length === 2 ) { LatLng.lat = vm._config.map.topojson.center[0]; LatLng.lon = vm._config.map.topojson.center[1]; } v...
{ L.GeoJSON.prototype.addData.call(this, jsonData); }
conditional_block
adv_YAN.py
_6/' + '{}.{}' DS_EMB_PATH = '/DATACENTER/data/pxd/bert_privacy/data/part_fake_6/'+'{}.{}' DANN_CPT_PATH = '/DATACENTER/data/yyf/Py/bert_privacy_Yan/data/Airline/DANN_CPT/' DANN_O_CPT_PATH = '/DATACENTER/data/yyf/Py/bert_privacy_Yan/data/Airline/DANN_Without_Valid_CPT/' MLP_CPT_P...
def _evaluate(self, x, y): preds = self.predict(x) # y = y.numpy() return np.mean(preds == y) def _evaluate_topk(self, x, y, k = K): # y = y.numpy() with torch.no_grad(): probs = self(x) _, topk = torch.topk(probs, k) topk = topk.cpu...
x = self(x) _loss = self.criterion(x, y) return _loss
identifier_body
adv_YAN.py
6/' + '{}.{}' DS_EMB_PATH = '/DATACENTER/data/pxd/bert_privacy/data/part_fake_6/'+'{}.{}' DANN_CPT_PATH = '/DATACENTER/data/yyf/Py/bert_privacy_Yan/data/Airline/DANN_CPT/' DANN_O_CPT_PATH = '/DATACENTER/data/yyf/Py/bert_privacy_Yan/data/Airline/DANN_Without_Valid_CPT/' MLP_CPT_PA...
(self, x, y, k = K): # y = y.numpy() with torch.no_grad(): probs = self(x) _, topk = torch.topk(probs, k) topk = topk.cpu().numpy() acc = [int(y[i] in topk[i, :]) for i in range(len(y))] return np.mean(acc) def fit(self, X, Y, test_X = None, t...
_evaluate_topk
identifier_name
adv_YAN.py
= data_utils.DataLoader(test_ds, batch_size = BATCH_SIZE, shuffle = True) for epoch in tqdm(range(epoch_num)): running_loss = 0.0 criterion = nn.CrossEntropyLoss() # optimizer = optim.SGD(self.parameters(), lr=0.1, momentum = 0.9) optimizer = optim.A...
util_clf.cuda() preds = util_clf.predict(Target_X) util_acc = np.mean(preds == target_util_y) # print("Util Acc. {:.4f}".format(acc))
random_line_split
adv_YAN.py
of [inputs, labels] inputs, labels = data inputs, labels = inputs.cuda(), labels.cuda() # zero the parameter gradients optimizer.zero_grad() # forward + backward + optimize outputs = self(inputs) loss = crit...
print("TRAINING SET SIZE: {}".format(len(Y))) print("EMBEDDINGS FROM TARGET DOMAIN: {}".format(len(Target_Y))) print("TEST SET SIZE: {}".format(len(Y_valid))) # learn a transfer print("TESTING MODEL: {}".format(CLS))
conditional_block
models.rs
Deserialize, Serialize, Clone)] pub struct KeywordStatistics { pub stats: KeywordStat, pub keyword_logs: Vec<Log>, } impl Statistics { pub fn new(account: Account) -> Self { Statistics { main_stats: MainStats::new(account), keyword_stats: HashMap::new(), } } } ...
// println!("Backup done"); let mut no_of_main_log_cleared = 0; { if count == 0 { let ms = &mut statistics.main
random_line_split
models.rs
, Serialize, Clone)] pub struct KeywordStatistics { pub stats: KeywordStat, pub keyword_logs: Vec<Log>, } impl Statistics { pub fn new(account: Account) -> Self { Statistics { main_stats: MainStats::new(account), keyword_stats: HashMap::new(), } } } pub type Db ...
} } #[derive(Debug, Deserialize, Serialize, Clone)] struct BackupStatistics { stats: MainStats, keyword: HashMap<KeywordId, Vec<Log>>, } // // We might want to reanalyze previous record for that we are providing ability to // // use old database. // pub async fn load_old_database() -> Option<Statistics> ...
{ main_stats.last_updated_at = crate::helpers::current_time_string(); if input.r#type == "error" { main_stats.error_counts += 1; ks.stats.error_counts += 1; } main_stats.log_counts += 1; ks.stats.log_counts += 1; ...
conditional_block
models.rs
, Serialize, Clone)] pub struct KeywordStatistics { pub stats: KeywordStat, pub keyword_logs: Vec<Log>, } impl Statistics { pub fn new(account: Account) -> Self { Statistics { main_stats: MainStats::new(account), keyword_stats: HashMap::new(), } } } pub type Db ...
{ pub id: u64, pub last_updated_at: String, pub error_counts: u64, pub log_counts: u64, pub name: Option<String>, pub keyword: Option<String>, pub placement: Option<u64>, pub running: Option<bool>, pub ads_running: Option<bool>, pub ads_position: Option<u64>, pub current_pr...
KeywordStat
identifier_name
tsviz.py
_path) == 0: return filename elif solution_path == ".": return filename else: return filename[len(solution_path)+1::] def get_friendly_id(self): return self.name.replace(".", "_").replace("-", "_").replace("/", "_") def add_dependency(self, module_na...
if match: module = match.groups()[0] full_module_path = self.get_module_path(module) result.append(full_module_path) match = module_require_declaration.match(item) if match: module = match.groups()[0] ful...
def get_module_imports(self, imports): result = [] for item in imports: match = module_import_declaration.match(item)
random_line_split
tsviz.py
_path) == 0: return filename elif solution_path == ".": return filename else: return filename[len(solution_path)+1::] def get_friendly_id(self): return self.name.replace(".", "_").replace("-", "_").replace("/", "_") def add_dependency(self, module_na...
def render_dot_file(projects, highlight_all=False, highlight_children=False): lines = [] lines.append("digraph {") lines.append(" rankdir=\"LR\"") lines.append("") lines.append(" # apply theme") lines.append(" bgcolor=\"#222222\"") lines.append("") lines.append(" // defau...
dep.highlighted_dependents = True
conditional_block
tsviz.py
(root_dir): global solution_path solution_path = get_directory(get_unix_path(root_dir)) debug("Base-solution dir set to {0}".format(solution_path)) class Module(object): def __init__(self, filename): self.name = self.get_name_from_filename(filename) self.filename = os.path.abspath(file...
set_working_basedir
identifier_name
tsviz.py
def get_name_from_filename(self, filename): if filename.find("/") == -1: return filename elif len(solution_path) == 0: return filename elif solution_path == ".": return filename else: return filename[len(solution_path)+1::] def ge...
def __init__(self, filename): self.name = self.get_name_from_filename(filename) self.filename = os.path.abspath(filename) self.dependant_module_names = [] # dependant modules, as declared in file. # not subject to transitive dependency-elimination. self.declared_dependan...
identifier_body
main.rs
); return; } } }; let Setup { file, socket_name, session, windows, rebuild: rebuilding, } = handle!(toml::from_str(&input), |err| { eprintln!("Input file (\"{}\") contains invalid toml: {}", path.display(), err); return; }); let rebuild = rebuild || rebuilding.unwrap_or(false); let file ...
} Err(err) => { eprintln!("Unable to create new session: {}", err); return; } } } // We rename the first window, so we can locate and remove it later. match tmux.rename_window(None, ORIGINAL_WINDOW_NAME) { Ok(v) => if !v.status.success() { eprintln!("Unable to rename default window: {:?}", v...
random_line_split
main.rs
(\"{}\") contains invalid toml: {}", path.display(), err); return; }); let rebuild = rebuild || rebuilding.unwrap_or(false); let file = file.as_ref().map(Deref::deref); let socket_name = socket_name.as_ref().map(Deref::deref); let Session { name: session_name, select, } = session.unwrap_or_default(); ...
{ return Some((left_index, right_index, *ordinal)); }
conditional_block
main.rs
if session already exists: {}", err); return; }); if has_session { // I've had some weird sessions where they just keep on sticking around. // Stupidest solution I've found is to just kill the server... :| handle!(tmux.kill_server(), |err| { eprintln!("Unable to kill server: {}", err); return; ...
Edge
identifier_name
rezepte.ts
export class Rezepte { recipes = []; foundRecipes = []; ingredient_CsC = []; ingredients_HOC = []; ingredients_Pizza = []; ingredients_Pommes = []; ingredients_birne = []; score: number; level2: number; level3: number; level4: number; level5: number; missingPoints = 0; constructor(public n...
@Component({ selector: 'page-rezepte', templateUrl: 'rezepte.html' })
random_line_split
rezepte.ts
0, co2value: 286}, {id: 65, title: 'Zucker', amount: 200, co2value: 335}, {id: 66, title: 'Wasser', amount: 500, co2value: 16}, {id: 67, title: 'Zitrone', amount: 85, co2value: 486}, {id: 68, title: 'Zimt (getrocknet)', amount: 15, co2value: 8106}, {id: 69, title: 'Nelken (getrocknet)', am...
howScore(){ let alert = this.alertCtrl.create({ title
identifier_body
rezepte.ts
: 286}, {id: 65, title: 'Zucker', amount: 200, co2value: 335}, {id: 66, title: 'Wasser', amount: 500, co2value: 16}, {id: 67, title: 'Zitrone', amount: 85, co2value: 486}, {id: 68, title: 'Zimt (getrocknet)', amount: 15, co2value: 8106}, {id: 69, title: 'Nelken (getrocknet)', amount: 5, co...
eine Punk
identifier_name
rezepte.ts
ipes = [ //http://app.eaternity.org/#!menu:7c5bd3c2-66a5-41f3-bd66-c35d40e8f4ae&customer=Eaternity&scope=PUBLIC { id: 0, title: 'Chili sin Carne', imageUrl: 'file:///android_asset/www/assets/img/0.jpg', category: 'einfach', co2: 497, recipeIngredients: this.ingredient_CsC, method: 'Die Zwiebel und Kar...
ecipe) { this.navCtrl.push(Reze
conditional_block
RecipeDetail.js
랙리스트에 올랐습니다.'){ console.log('black list') // localStorage.removeItem('tokens') } if(error.response.data.status_code == 401 || error.response.data.status_code == 500){ alert('다시 로그인해야합니다.') window.location.href = '/logout?redirect_url=recipe/'+r...
lues(options); const {languages} = this.state; let {type_lang} = this.state; let lang = localStorage.getItem('lang'); if(lang) type_lang = lang; languages.setLanguage(type_lang); for(var i = 0; i < optionsCount; i++) { if(_optionsArray[i].id == _id) { var _text = _...
options} = this.state; const _optionsArray = Object.va
identifier_body
RecipeDetail.js
�랙리스트에 올랐습니다.'){ console.log('black list') // localStorage.removeItem('tokens') } if(error.response.data.status_code == 401 || error.response.data.status_code == 500){ alert('다시 로그인해야합니다.') window.location.href = '/logout?redirect_url=recipe/'+...
}) .catch(error => { if(error.response.data.status_code == 401){ alert('다시 로그인해야합니다.') window.location.href = '/logout?redirect_url=recipe/'+recipeId+'/detail' } }); } resetErrors() { this.setState({ errors: {}, ...
if(saving == false) this.setState({saving: true}); else this.setState({saving: false});
random_line_split
RecipeDetail.js
랙리스트에 올랐습니다.'){ console.log('black list') // localStorage.removeItem('tokens') } if(error.response.data.status_code == 401 || error.response.data.status_code == 500){ alert('다시 로그인해야합니다.') window.location.href = '/logout?redirect_url=recipe/'+r...
(type_lang == "en") { _text = (detail.cate_detail.title_en != null) ? detail.cate_detail.title_en : detail.cate_detail.title; } else if (type_lang == "cn") { _text = (detail.cate_detail.title_cn != null) ? detail.cate_detail.title_cn : detail.cate_detail.title; } return _text; ...
e; if
identifier_name
shoot_ball.js
); } // // Configure WebGL // gl.enable(gl.DEPTH_TEST); gl.depthMask(true); gl.depthFunc(gl.LEQUAL); gl.depthRange(0.0, 1.0); //Init score stuff scoreCounter = document.getElementById("scoreCounter"); scoreCounter.innerHTML = "Score: " + actualScore; missCounter = docu...
//If out of misses, reset game state while saving the new high score if necessary if(actualMissCount == 0) { if(actualScore > actualhighScore) { actualhighScore = actualScore; } alert("Out of misses! You got " + actualScore + " points this roun...
{ for(var i = 0; i < velocities.length; i++){ //Move the ball by its velocity for(var j = 0; j < (pointsAroundCircle + 2); j++){ ballVertices[(pointsAroundCircle + 2) * i + j] = add(ballVertices[(pointsAroundCircle + 2) * i + j], velocities[i]); } //Add acceleration to the velocity v...
identifier_body
shoot_ball.js
value; var velMagnitude = initVel * power; var xVel = velMagnitude * Math.sin(radians(angleY)) * Math.sin(radians(angleX)); var yVel = velMagnitude * Math.cos(radians(angleX)); var zVel = velMagnitude * Math.cos(radians(angleY)) * Math.sin(radians(angleX)); velocities.push(vec3(xVel, yVel...
loadTexture
identifier_name
shoot_ball.js
); } // // Configure WebGL // gl.enable(gl.DEPTH_TEST); gl.depthMask(true); gl.depthFunc(gl.LEQUAL); gl.depthRange(0.0, 1.0); //Init score stuff scoreCounter = document.getElementById("scoreCounter"); scoreCounter.innerHTML = "Score: " + actualScore; missCounter = docu...
} //Check for collisions else{ let ballCenter = ballVertices[(pointsAroundCircle + 2) * i]; for(let x = 0; x < centerList.length; x++) { let a = centerList[x][0] - ballCenter[0]; let b = centerList[x][1] - ballCenter[1]; let c = centerList[x][2] -...
{ if(actualScore > actualhighScore) { actualhighScore = actualScore; } alert("Out of misses! You got " + actualScore + " points this round."); actualScore = 0; scoreCounter.innerHTML = "Score: " + actualScore; actualMissCount = 5; ...
conditional_block
shoot_ball.js
} // // Configure WebGL // gl.enable(gl.DEPTH_TEST); gl.depthMask(true); gl.depthFunc(gl.LEQUAL); gl.depthRange(0.0, 1.0); //Init score stuff scoreCounter = document.getElementById("scoreCounter"); scoreCounter.innerHTML = "Score: " + actualScore; missCounter = documen...
actualMissCount--; missCounter.innerHTML = "Misses left: " + actualMissCount; //If out of misses, reset game state while saving the new high score if necessary if(actualMissCount == 0) { if(actualScore > actualhighScore) { actualhighScore = actualS...
i--; ballIndex--;
random_line_split
t_usefulness.rs
fn kernel_i16(data: [i16x8; 8]) -> [i16x8; 8] { // kernel x let a2 = data[2]; let a6 = data[6]; let b0 = a2.saturating_add(a6).mul_scale_round_n(to_fixed(0.5411961)); let c0 = b0 .saturating_sub(a6) .saturating_sub(a6.mul_scale_round_n(to_fixed(0.847759065))); let c1 = b0.satura...
{ (x * 32767.0 + 0.5) as i16 }
identifier_body
t_usefulness.rs
let a_expected = f32x4::from([255.0, 255.0, 255.0, 255.0]); assert_eq!(r_expected, r_actual); assert_eq!(g_expected, g_actual); assert_eq!(b_expected, b_actual); assert_eq!(a_expected, a_actual); // modify some of the data let r_new = (r_actual - f32x4::from(1.0)).max(f32x4::from(0.0)); let g_new = (g_...
let r_expected = f32x4::from([255.0, 0.0, 0.0, 0.0]); let g_expected = f32x4::from([0.0, 255.0, 0.0, 0.0]); let b_expected = f32x4::from([0.0, 0.0, 255.0, 0.0]);
random_line_split
t_usefulness.rs
} fn
(data: [i16x8; 8]) -> [i16x8; 8] { // kernel x let a2 = data[2]; let a6 = data[6]; let b0 = a2.saturating_add(a6).mul_scale_round_n(to_fixed(0.5411961)); let c0 = b0 .saturating_sub(a6) .saturating_sub(a6.mul_scale_round_n(to_fixed(0.847759065))); let c1 = b0.saturating_add(a2.mul_s...
kernel_i16
identifier_name
page.js
function(initData) { if (typeof initData == "object") { for(var key in initData) { that.$set(key, initData[key]); } } }); that.$update = function(initData) { that.$emit("__updateData", initData); } ...
this.$parent; } else { $wrap = $(this.$el); mgpage = {params: null, wrapper: null}; mgpage.wrapper = $wrap; mgpage.params = {}; } // 给包含容器添加私有的样式类 if (page && page.style && ...
this.$appendTo($wrap[0]); $wrap[0].MG_CHILDREN = this; mgpage.mgwrap =
conditional_block
page.js
", function(initData) { if (typeof initData == "object") { for(var key in initData) { that.$set(key, initData[key]); } } }); that.$update = function(initData) { that.$emit("__updateData", initData); } ...
if (this.$el.nodeType === 3) { this.$el = this.$el.nextElementSibling; this._isFragment = false; } this.$appendTo($wrap[0]); $wrap[0].MG_CHILDREN = this; mgpage.mgwrap = ...
if ($parent && $parent.$options.name == "mgRender") { mgpage = $parent.MG_PAGE; $wrap = mgpage.wrapper;
random_line_split
page.js
"+name; ret = ret.replace(/[\-|\\|\/]/g, "-"); return tag ? "<"+ret+"></"+ret+">" : ret; } /** * 参数值修正,转换000为空 */ function _transParams(params) { for (var key in params) { if (params[key] == "000") { params[key] = ""; } } ...
ar ret = "ma-
identifier_name
page.js
*/ function _transParams(params) { for (var key in params) { if (params[key] == "000") { params[key] = ""; } } return params; } /** * 如果页面没有 resolve 方法,初始化操作 */ function pageDefaultInit(_params) { var that = this; ...
ret = ret.replace(/[\-|\\|\/]/g, "-"); return tag ? "<"+ret+"></"+ret+">" : ret; } /** * 参数值修正,转换000为空
identifier_body
api_op_PostText.go
continue on another device, use a user-specific // identifier. // // * If you want the same user to be able to have two independent // conversations on two different devices, choose a device-specific identifier. // // // * A user can't have two independent conversations with two different versions of // th...
{ err = stack.Serialize.Add(&awsRestjson1_serializeOpPostText{}, middleware.After) if err != nil { return err } err = stack.Deserialize.Add(&awsRestjson1_deserializeOpPostText{}, middleware.After) if err != nil { return err } awsmiddleware.AddRequestInvocationIDMiddleware(stack) smithyhttp.AddContentLengthM...
identifier_body
api_op_PostText.go
Lex messages require a user response. // For example, a conclusion statement does not require a response. Some messages // require only a "yes" or "no" user response. In addition to the message, Amazon // Lex provides additional context about the message in the response that you might // use to enhance client behavior...
// expecting a "yes" or "no" response. For example, Amazon Lex wants user // confirmation before fulfilling an intent. Instead of a simple "yes" or "no," a // user might respond with additional information. For example, "yes, but make it // thick crust pizza" or "no, I want to order a drink". Amazon Lex can process...
// wants to elicit user intent. For example, a user might utter an intent ("I want // to order a pizza"). If Amazon Lex cannot infer the user intent from this // utterance, it will return this dialogState. // // * ConfirmIntent - Amazon Lex is
random_line_split
api_op_PostText.go
a device-specific identifier. // // // * A user can't have two independent conversations with two different versions of // the same bot. For example, a user can't have a conversation with the PROD and // BETA versions of the same bot. If you anticipate that a user will need to have // conversation with two diffe...
newServiceMetadataMiddleware_opPostText
identifier_name
api_op_PostText.go
messages require a user response. // For example, a conclusion statement does not require a response. Some messages // require only a "yes" or "no" user response. In addition to the message, Amazon // Lex provides additional context about the message in the response that you might // use to enhance client behavior, fo...
out := result.(*PostTextOutput) out.ResultMetadata = metadata return out, nil } type PostTextInput struct { // The alias of the Amazon Lex bot. // // This member is required. BotAlias *string // The name of the Amazon Lex bot. // // This member is required. BotName *string // The text that the user en...
{ return nil, err }
conditional_block
controller.py
de waypoint est envoyé dans le service /mavros/mission/set_current afin d'effectuer à nouveau la fauchée. - Diagnostique Documentation : - http://wiki.ros.org/mavros_msgs """ import rospy import rospkg from std_msgs.msg import Int16 from sensor_msgs.msg import BatteryState from ma...
""" Callback appelé lors de la réception d'un msg sur /warning - Appel des fonctions wpt_chang() et stop() Entrée : data : Int16 """ self.warning = data.data rospy.logwarn("Warning, type" + str(self.warning)) if (self.warning != -1): s...
, data):
identifier_name
controller.py
de waypoint est envoyé dans le service /mavros/mission/set_current afin d'effectuer à nouveau la fauchée. - Diagnostique Documentation : - http://wiki.ros.org/mavros_msgs """ import rospy import rospkg from std_msgs.msg import Int16 from sensor_msgs.msg import BatteryState from ma...
: nav_msg.value = "Trav" self.nav_pub.publish(nav_msg) #----------Debut de ligne ---------------------- elif data.waypoints[data.current_seq].param1 == 0: if data.waypoints[self.current_wp].param1 == 1: rospy.loginfo("Début de ligne") ...
else
conditional_block
controller.py
de waypoint est envoyé dans le service /mavros/mission/set_current afin d'effectuer à nouveau la fauchée. - Diagnostique Documentation : - http://wiki.ros.org/mavros_msgs """ import rospy import rospkg from std_msgs.msg import Int16 from sensor_msgs.msg import BatteryState from ma...
self.battery_min = battery_min self.wp_enregistre = 0 self.wp_number = 0 self.current_wp = 0 self.last_waypoint = 0 self.waypoint_warning = 0 self.arming="Disarmed" #Armed or Disarmed self.mode="HOLD" #HOLD, LOITER, AUTO, MANUAL def battery_callbac...
random_line_split
controller.py
de waypoint est envoyé dans le service /mavros/mission/set_current afin d'effectuer à nouveau la fauchée. - Diagnostique Documentation : - http://wiki.ros.org/mavros_msgs """ import rospy import rospkg from std_msgs.msg import Int16 from sensor_msgs.msg import BatteryState from mavros_msgs...
: """ Fonction lors de la réception d'un warning publie la consigne du wpt de correction sur le service /mavros/mission/set_current. Le wpt de correction est le dernier de la ligne précedente. Mise à zéro de la variable warning """ if self.waypoints_list[self.wa...
ppelé lors de la réception d'un msg sur /warning - Appel des fonctions wpt_chang() et stop() Entrée : data : Int16 """ self.warning = data.data rospy.logwarn("Warning, type" + str(self.warning)) if (self.warning != -1): self.waypoint_warning = ...
identifier_body
lfs.go
, repositoryLocation, err := openContainingRepository(filename) if err != nil { return "", err } // Check if the file has been changed and commit it if it has. changed, err := fileChanged(repo, filename) if err != nil { return "", err } var commitId string if changed { err := addToIndex(repo, filename)...
{ repo, _, err := openRepository(hostpath) if err != nil { return "", errors.Wrap(err, "Could not open repository") } ref, err := repo.Head() if err != nil { return "", errors.Wrap(err, "Could not get head") } head := ref.Target() return head.String(), nil }
identifier_body
lfs.go
return "", err } } return commitId, nil } // Add a file to the index func
(filename string) error { // Open repository at path. repo, _, err := openContainingRepository(filename) if err != nil { return err } // Check if the file has been changed and commit it if it has. changed, err := fileChanged(repo, filename) if err != nil { return err } if changed { err := addToIndex(re...
Add
identifier_name
lfs.go
return "", err } } return commitId, nil } // Add a file to the index func Add(filename string) error { // Open repository at path. repo, _, err := openContainingRepository(filename) if err != nil { return err } // Check if the file has been changed and commit it if it has. changed, err := fileChanged(...
} else { break } } return repo, path, nil } // git add // To speed up dev time for the prototype, use the exec pkg not git2go package // to add files. Future versions will get rid of this hacky way of doing things // by creating the blobs, softlinks etc. but that's for later! func add(path, repositoryLocatio...
{ path = wd log.Println("Output directory is not in a git repository. Creating one in " + path) repo, err = git.InitRepository(wd, false) if err != nil { return nil, "", errors.Wrap(err, "Could not initialize git repository") } break }
conditional_block
lfs.go
// if pattern already exists don't rerun the track command b, err := ioutil.ReadFile(gitAttr) if err != nil { pe := err.(*os.PathError) if pe.Err.Error() != "no such file or directory" { return false, "", err } } if !strings.Contains(string(b), dataPattern) { output, err := Track(dataPattern, repositor...
path, err := filepath.Abs(path) if err != nil { return errors.Wrap(err, "Could not get absolute path of output directory")
random_line_split
pip_test.go
{"setuppy", "setuppyproject", "setuppy", "jfrog-python-example", []string{"pip-install", ".", "--no-cache-dir", "--force-reinstall", "--build-name=" + tests.PipBuildName}, 3, true}, {"setuppy-verbose", "setuppyproject", "setuppy-verbose", "jfrog-python-example", []string{"pip-install", ".", "--no-cache-dir", "--for...
{"setuppy", "setuppyproject", "setuppy", "jfrog-python-example", []string{".", "--no-cache-dir", "--force-reinstall"}, 3, true}, {"setuppy-verbose", "setuppyproject", "setuppy-verbose", "jfrog-python-example", []string{".
moduleId string args []string expectedDependencies int cleanAfterExecution bool }{
random_line_split
pip_test.go
{"setuppy", "setuppyproject", "setuppy", "jfrog-python-example", []string{"pip-install", ".", "--no-cache-dir", "--force-reinstall", "--build-name=" + tests.PipBuildName}, 3, true}, {"setuppy-verbose", "setuppyproject", "setuppy-verbose", "jfrog-python-example", []string{"pip-install", ".", "--no-cache-dir", "--forc...
func (pfc *PipCmd) GetErrWriter() io.WriteCloser { return nil } func TestPipDepsTree(t *testing.T) { initPipTest(t) // Add virtual-environment path to 'PATH' for executing all pip and python commands inside the virtual-environment. pathValue := setPathEnvForPipInstall(t) if t.Failed() { t.FailNow() } defer...
{ return nil }
identifier_body
pip_test.go
{"setuppy", "setuppyproject", "setuppy", "jfrog-python-example", []string{"pip-install", ".", "--no-cache-dir", "--force-reinstall", "--build-name=" + tests.PipBuildName}, 3, true}, {"setuppy-verbose", "setuppyproject", "setuppy-verbose", "jfrog-python-example", []string{"pip-install", ".", "--no-cache-dir", "--forc...
defer os.Chdir(wd) args = append(args, "--build-number="+buildNumber) err = artifactoryCli.Exec(args...) if err != nil { t.Errorf("Failed executing pip-install command: %s", err.Error()) cleanPipTest(t, outputFolder) return } artifactoryCli.Exec("bp", tests.PipBuildName, buildNumber) buildInfo := intt...
{ t.Error(err) }
conditional_block
pip_test.go
{"setuppy", "setuppyproject", "setuppy", "jfrog-python-example", []string{"pip-install", ".", "--no-cache-dir", "--force-reinstall", "--build-name=" + tests.PipBuildName}, 3, true}, {"setuppy-verbose", "setuppyproject", "setuppy-verbose", "jfrog-python-example", []string{"pip-install", ".", "--no-cache-dir", "--forc...
() io.WriteCloser { return nil } func (pfc *PipCmd) GetErrWriter() io.WriteCloser { return nil } func TestPipDepsTree(t *testing.T) { initPipTest(t) // Add virtual-environment path to 'PATH' for executing all pip and python commands inside the virtual-environment. pathValue := setPathEnvForPipInstall(t) if t.F...
GetStdWriter
identifier_name
porcelain.go
, increment the queried route with the missing parts if hint != nil { route = addHintToRoute(route, *hint, payee, delayFinalHop) } // inspect route, it shouldn't be too expensive if route.Get("0.msatoshi").Float()/msatoshi > (1 + 1/maxfeepercent) { // too expensive, but we'll still accept it if the payme...
{ if int64(h) == fullHint.Get("#").Int()-1 { // this is the first iteration, means it's the last hint channel/hop nextmsat = lastPublicHop.Get("msatoshi").Int() // this is the final amount, yes it is. nextdelay = finalHopDelay nextpeer = finalPeer delaydelta = 0 fees = 0 } else { // now we'll get the va...
identifier_body
porcelain.go
key").String() } res, err := ln.CallNamed("getroute", "id", target, "riskfactor", riskfactor, "cltv", delayFinalHop, "msatoshi", msatoshi, "fuzzpercent", 0, "exclude", *exclude, ) if err != nil { // no route or invalid parameters, call it a simple failure return } if !res.Get("rout...
{ // this is the first iteration, means it's the last hint channel/hop nextmsat = lastPublicHop.Get("msatoshi").Int() // this is the final amount, yes it is. nextdelay = finalHopDelay nextpeer = finalPeer delaydelta = 0 fees = 0 }
conditional_block
porcelain.go
// It's like the default 'pay' plugin, but it blocks until a final success or failure is achieved. // After it returns you can be sure a failed payment will not succeed anymore. // Any value in params will be passed to 'getroute' or 'sendpay' or smart defaults will be used. // This includes values from the default 'pay...
// PayAndWaitUntilResolution implements its 'pay' logic, querying and retrying routes.
random_line_split
porcelain.go
' or 'sendpay' or smart defaults will be used. // This includes values from the default 'pay' plugin. func (ln *Client) PayAndWaitUntilResolution( bolt11 string, params map[string]interface{}, ) (success bool, payment gjson.Result, tries []Try, err error) { decoded, err := ln.Call("decodepay", bolt11) if err != nil...
( route gjson.Result, hint gjson.Result, finalPeer string, finalHopDelay int64, ) gjson.Result { var extrafees int64 = 0 // these extra fees will be added to the public part var extradelay int64 = 0 // this extra delay will be added to the public part // we know exactly the length of our new route npublichops :...
addHintToRoute
identifier_name
ProgramsTab.py
, make_title_border, HTMLRenderer, CallbackActionListener, ) from javax.swing.BorderFactory import createEmptyBorder from helpers import async_call, same_size import context def guess_scope(s): domain_pattern = re.compile( ( r"^" r"(?:(?P<protocol>https?)://)?" ...
class TitleBtnBox(FixedColumnPanel): def __init__(self, program): url = "https://yeswehack.com/programs/{}".format(program.slug) btn = JButton("Open in browser") btn.addActionListener( CallbackActionListener(lambda _: Desktop.getDesktop().browse(URI(url))) ) sel...
html_renderer = HTMLRenderer(html) html_renderer.add_css_file("style.css") JScrollPane.__init__(self, html_renderer) self.setBorder(make_title_border("Rules"))
random_line_split
ProgramsTab.py
, make_title_border, HTMLRenderer, CallbackActionListener, ) from javax.swing.BorderFactory import createEmptyBorder from helpers import async_call, same_size import context def guess_scope(s): domain_pattern = re.compile( ( r"^" r"(?:(?P<protocol>https?)://)?" ...
self.setForeground(Color.black) self.setText(program.title) self.setOpaque(1) self.setBorder(createEmptyBorder(5, 10, 5, 10)) return self class ProgramsTab(JPanel): def __init__(self): self.programs = [] self.setLayout(BoxLayout(self, BoxLayout.PAGE_A...
self.setBackground(Color(0xFFDDDDD))
conditional_block
ProgramsTab.py
, make_title_border, HTMLRenderer, CallbackActionListener, ) from javax.swing.BorderFactory import createEmptyBorder from helpers import async_call, same_size import context def guess_scope(s): domain_pattern = re.compile( ( r"^" r"(?:(?P<protocol>https?)://)?" ...
(self, scope_list, event): config = json.loads(context.callbacks.saveConfigAsJson("target.scope")) config["target"]["scope"]["advanced_mode"] = True for maybe_url in scope_list.getSelectedValues(): url = guess_scope(maybe_url) if url: config["target"]["sc...
add_to_scope
identifier_name
ProgramsTab.py
, make_title_border, HTMLRenderer, CallbackActionListener, ) from javax.swing.BorderFactory import createEmptyBorder from helpers import async_call, same_size import context def guess_scope(s): domain_pattern = re.compile( ( r"^" r"(?:(?P<protocol>https?)://)?" ...
config["proxy"]["match_replace_rules"], ) new_rule = { "is_simple_match": False, "enabled": True, "rule_type": "request_header", "string_match": "^User-Agent: (.*)$", "string_replace": "User-Agent: $1...
def __init__(self, program): self.setLayout(GridBagLayout()) self.setBorder(make_title_border("User-Agent", padding=5)) btn = JButton("Add to settings") ua_text = JTextField(program.user_agent) self.add( ua_text, make_constraints(weightx=4, fill=GridBagConstraints.HOR...
identifier_body
cluster.go
. package m3 import ( "errors" "fmt" "io" "sync" "time" "github.com/m3db/m3/src/dbnode/client" "github.com/m3db/m3/src/query/storage/m3/storagemetadata" xerrors "github.com/m3db/m3/src/x/errors" "github.com/m3db/m3/src/x/ident" ) var ( errNamespaceIDNotSet = errors.New("namespace ID not set") errSessio...
return *o.downsample, nil } // ClusterNamespaceDownsampleOptions is the downsample options for // a cluster namespace. type ClusterNamespaceDownsampleOptions struct { All bool } // ClusterNamespaces is a slice of ClusterNamespace instances. type ClusterNamespaces []ClusterNamespace // NumAggregatedClusterNamespac...
{ return DefaultClusterNamespaceDownsampleOptions, nil }
conditional_block
cluster.go
. package m3 import ( "errors" "fmt" "io" "sync" "time" "github.com/m3db/m3/src/dbnode/client" "github.com/m3db/m3/src/query/storage/m3/storagemetadata" xerrors "github.com/m3db/m3/src/x/errors" "github.com/m3db/m3/src/x/ident" ) var ( errNamespaceIDNotSet = errors.New("namespace ID not set") errSessio...
// ReadOnly returns the value of ReadOnly option for a cluster namespace. func (o ClusterNamespaceOptions) ReadOnly() bool { return o.readOnly } // DownsampleOptions returns the downsample options for a cluster namespace, // which is only valid if the namespace is an aggregated cluster namespace. func (o ClusterNam...
{ return o.dataLatency }
identifier_body
cluster.go
" "github.com/m3db/m3/src/x/ident" ) var ( errNamespaceIDNotSet = errors.New("namespace ID not set") errSessionNotSet = errors.New("session not set") errRetentionNotSet = errors.New("retention not set") errResolutionNotSet = errors.New("resolution not set") errNegativeDataLatency = errors.New("neg...
newUnaggregatedClusterNamespace
identifier_name
cluster.go
SOFTWARE. package m3 import ( "errors" "fmt" "io" "sync" "time" "github.com/m3db/m3/src/dbnode/client" "github.com/m3db/m3/src/query/storage/m3/storagemetadata" xerrors "github.com/m3db/m3/src/x/errors" "github.com/m3db/m3/src/x/ident" ) var ( errNamespaceIDNotSet = errors.New("namespace ID not set") ...
expectedAggregated) def := unaggregatedClusterNamespace unaggregatedNamespace, err := newUnaggregatedClusterNamespace(def) if err != nil { return nil, err } namespaces = append(namespaces, unaggregatedNamespace) for _, def := range aggregatedClusterNamespaces { namespace, err := newAggregatedClusterNamesp...
random_line_split
switch.go
make( map[string]bool, 64 ) s.hport = make( map[string]int, 64 ) s.hvmid = make( map[string]*string, 64 ) return } /* Destruction */ func (s *Switch) Nuke() { for i := 0; i < s.lidx; i++ { s.links[i] = nil } s.links = nil s.hosts = nil s.hport = nil } /* Add a link to the switch. */ func (s *Switch) Add...
( target *string, commence, conclude, inc_cap int64, usr *string, usr_max int64 ) ( found *Switch, cap_trip bool ) { var ( fsw *Switch // next neighbour switch (through link) ) found = nil cap_trip = false //fmt.Printf( "\n\nsearching neighbours of (%s) for %s\n", s.To_str(), *target ) for i := 0; i < s.lid...
probe_neighbours
identifier_name
switch.go
} found, cap_trip = sw.probe_neighbours( target, commence, conclude, inc_cap, usr, usr_max ) if found != nil { return } if cap_trip { lcap_trip = true // must preserve this } if sw.Flags & tegu.SWFL_VISITED == 0 { // possible that it was pushed multiple times and already had it's neighbours ...
sep = ","
random_line_split
switch.go
_cap of 0, but that seems silly. */ func (s *Switch) Path_to( target *string, commence, conclude, inc_cap int64, usr *string, usr_max int64 ) ( found *Switch, cap_trip bool ) { var ( sw *Switch fifo []*Switch push int = 0 pop int = 0 pidx int = 0 lcap_trip bool = false // local detection of capac...
{ if s == nil { return false } for i := 0; i < s.lidx; i++ { has_room, err := s.links[i].Has_capacity( commence, conclude, inc_cap, usr, usr_max ) if ! has_room { obj_sheep.Baa( 2, "switch/cap_out: no capacity on link from %s: %s", s.id, err ) return false } } obj_sheep.Baa( 2, "switch/cap_out: %s ...
identifier_body
switch.go
make( map[string]bool, 64 ) s.hport = make( map[string]int, 64 ) s.hvmid = make( map[string]*string, 64 ) return } /* Destruction */ func (s *Switch) Nuke() { for i := 0; i < s.lidx; i++ { s.links[i] = nil } s.links = nil s.hosts = nil s.hport = nil } /* Add a link to the switch. */ func (s *Switch) Add...
return s.id } /* Return the ith link in our index or nil if i is out of range. Allows the user programme to loop through the list if needed. Yes, this _could_ have been implemented to drive a callback for each list element, but that just makes the user code more complicated requiring an extra function or closu...
{ return nil }
conditional_block
message.go
var msg verACK return &msg, nil case "getheaders": var msg headersReq return &msg, nil case "headers": var msg blkHeader return &msg, nil case "getaddr": var msg addrReq return &msg, nil case "addr": var msg addr return &msg, nil case "inv": var msg inv // the 1 is the inv type lenght msg....
serialization
identifier_name