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
utils.py
#! /usr/bin/env python ############################################################################ ## util.py ## ## Part of the DendroPy library for phylogenetic computing. ## ## Copyright 2008 Jeet Sukumaran and Mark T. Holder. ## ## This program is free software; you can redistribute it and/or modify ## it und...
"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
#! /usr/bin/env python ############################################################################ ## util.py ## ## Part of the DendroPy library for phylogenetic computing. ## ## Copyright 2008 Jeet Sukumaran and Mark T. Holder. ## ## This program is free software; you can redistribute it and/or modify ## it und...
(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
#! /usr/bin/env python ############################################################################ ## util.py ## ## Part of the DendroPy library for phylogenetic computing. ## ## Copyright 2008 Jeet Sukumaran and Mark T. Holder. ## ## This program is free software; you can redistribute it and/or modify ## it und...
else: return True else: if complement: return True else: return False def find_files(top, recursive=True, filename_filter=None, dirname_filter=None, excludes=None, co...
return False
conditional_block
utils.py
#! /usr/bin/env python ############################################################################ ## util.py ## ## Part of the DendroPy library for phylogenetic computing. ## ## Copyright 2008 Jeet Sukumaran and Mark T. Holder. ## ## This program is free software; you can redistribute it and/or modify ## it und...
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
/** * index scirpt for Zhangshuo Guoranhao */ define('index', ['common'], function(require, exports, module){ var common = require('common'); // 首页 命名空间 var pub = {}; pub.openId = common.openId.getItem(); pub.accountRelatived = common.accountRelatived.getItem(); pub.dfd = $.Deferred();//主要用于商品接口的延时对象 ...
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
/** * index scirpt for Zhangshuo Guoranhao */ define('index', ['common'], function(require, exports, module){ var common = require('common'); // 首页 命名空间 var pub = {}; pub.openId = common.openId.getItem(); pub.accountRelatived = common.accountRelatived.getItem(); pub.dfd = $.Deferred();//主要用于商品接口的延时对象 ...
pub.accountRelative.done( pub.apiHandle.weixin_binding.init ); // 账户绑定接口 */ // 微信授权处理 // !pub.openId && common.isWeiXin() && pub.weixinCode && pub.get_weixin_code(); common.lazyload(); // 懒加载 pub.eventHandle.init(); // 模块初始化事件处理 $('.footer_item[data-content]','#foot').attr('data-c...
!pub.accountRelatived && pub.logined && pub.accountRelative.resolve(); // 关联 }()); }());
random_line_split
main.rs
extern crate regex; pub mod dict; pub mod dictionary; pub mod idx; pub mod ifo; pub mod reformat; pub mod result; pub mod syn; //pub mod web; use self::regex::bytes::Regex; use std::cmp::Ordering; use std::io::prelude::*; use std::iter::Iterator; use std::mem; use std::net::TcpListener; use std::net::TcpStream; use s...
else if surl.path[0] == b'w' { content.extend(HOME_PAGE.as_bytes()); } } else { content.extend(HOME_PAGE.as_bytes()); } } fn map_by_file(f: &[u8]) -> &'static [u8] { if let Some(s) = f.rsplit(|c| *c == b'.').next() { match s { ...
{ //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
extern crate regex; pub mod dict; pub mod dictionary; pub mod idx; pub mod ifo; pub mod reformat; pub mod result; pub mod syn; //pub mod web; use self::regex::bytes::Regex; use std::cmp::Ordering; use std::io::prelude::*; use std::iter::Iterator; use std::mem; use std::net::TcpListener; use std::net::TcpStream; use s...
/// 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
extern crate regex; pub mod dict; pub mod dictionary; pub mod idx; pub mod ifo; pub mod reformat; pub mod result; pub mod syn; //pub mod web; use self::regex::bytes::Regex; use std::cmp::Ordering; use std::io::prelude::*; use std::iter::Iterator; use std::mem; use std::net::TcpListener; use std::net::TcpStream; use s...
<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
extern crate regex; pub mod dict; pub mod dictionary; pub mod idx; pub mod ifo; pub mod reformat; pub mod result; pub mod syn; //pub mod web; use self::regex::bytes::Regex; use std::cmp::Ordering; use std::io::prelude::*; use std::iter::Iterator; use std::mem; use std::net::TcpListener; use std::net::TcpStream; use s...
} else if surl.path[0] == b'r' { stream.write(map_by_file(&surl.word))?; } else { stream.write(b"text/html")?; } stream.write(b"\r\nContent-Length: ")?; stream.write(content.len().to_string().as_bytes())?; stream.write(b"\r\nConnection: close\r\n\r...
if surl.path[0] == b'n' { stream.write(b"text/plain")?;
random_line_split
jsontest.js
//assuming this comes from an ajax call var info = [{ "Event": "Pals - The Irish at Gallipoli", "Start Date": "1st April 2015", "Finish Date": "31st April 2015", "Time": "During Museum opening hours", "Location": "Decorative Arts & History", "Description": "As part of the Museum's WW1 centenary...
"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
//assuming this comes from an ajax call var info = [{ "Event": "Pals - The Irish at Gallipoli", "Start Date": "1st April 2015", "Finish Date": "31st April 2015", "Time": "During Museum opening hours", "Location": "Decorative Arts & History", "Description": "As part of the Museum's WW1 centenary...
ey) { var 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 js = JSON....
es(obj, k
identifier_name
jsontest.js
//assuming this comes from an ajax call var info = [{ "Event": "Pals - The Irish at Gallipoli", "Start Date": "1st April 2015", "Finish Date": "31st April 2015", "Time": "During Museum opening hours", "Location": "Decorative Arts & History", "Description": "As part of the Museum's WW1 centenary...
s = JSON.parse(json); console.log(getValues(js,'ID')); $(document).on("pageinit", "#info-page", function () { var li = ""; $.each(info, function (i,Event) { li += '<li><a href="#" id="' + i + '" class="info-go">' + Event.Event + '</a></li>'; }); $("#prof-list").append(li).promise().done(fun...
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
import argparse as agp import getpass import os from myTools import MSSQL_DBConnector as mssql from myTools import DBConnector as dbc import myTools.ContentObfuscation as ce try: import pandas as pd except: mi.installModule("pandas") import pandas as pd def printSplashScreen(): print("************...
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
import argparse as agp import getpass import os from myTools import MSSQL_DBConnector as mssql from myTools import DBConnector as dbc import myTools.ContentObfuscation as ce try: import pandas as pd except: mi.installModule("pandas") import pandas as pd def printSplashScreen(): print("************...
#Compare the existing pickled SurveyStructure file with surveyStructureDF # What do you need to do if the dataframe and the pickled file are different? #TODO #pass #pass only written here for not creating a syntax error, to be removed ...
#TODO refreshViewInDB(connector, getAllSurveyDataQuery(connector), cliArguments['viewname']) else:
random_line_split
Python_SQL_Project_CodeBase-DA.py
import argparse as agp import getpass import os from myTools import MSSQL_DBConnector as mssql from myTools import DBConnector as dbc import myTools.ContentObfuscation as ce try: import pandas as pd except: mi.installModule("pandas") import pandas as pd def printSplashScreen(): print("************...
else: print("Inconsistency: CLI argument dictionary is None. Exiting") return if __name__ == '__main__': main()
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
import argparse as agp import getpass import os from myTools import MSSQL_DBConnector as mssql from myTools import DBConnector as dbc import myTools.ContentObfuscation as ce try: import pandas as pd except: mi.installModule("pandas") import pandas as pd def printSplashScreen(): print("************...
(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
/* Copyright 2015 The Kubernetes 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 to in writing, ...
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.watchers[gvr]; !exists { t.watchers[gvr] = make(map[string][]*watch.RaceFreeFakeWatcher) } t.watchers[gvr][ns] = append(...
{ // 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
/* Copyright 2015 The Kubernetes 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 to in writing, ...
} 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
/* Copyright 2015 The Kubernetes 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 to in writing, ...
(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
/* Copyright 2015 The Kubernetes 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 to in writing, ...
for _, obj := range list { if err := t.Add(obj); err != nil { return err } } return nil } func (t *tracker) Delete(gvr schema.GroupVersionResource, ns, name string) error { t.lock.Lock() defer t.lock.Unlock() objs, ok := t.objects[gvr] if !ok { return errors.NewNotFound(gvr.GroupResource(), name) } ...
{ return errs[0] }
conditional_block
lib.rs
// Copyright 2020 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in w...
// 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
// Copyright 2020 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in w...
/// Generate the Rust bindings. Call `generate` first. pub fn generate_rs(&self) -> TokenStream2 { match &self.state { State::NotGenerated => panic!("Call generate() first"), State::Generated(itemmod, _) => itemmod.to_token_stream(), State::NothingGenerated | State:...
{ 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
// Copyright 2020 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in w...
(&self) -> Result<Vec<PathBuf>> { self.determine_incdirs() } }
include_dirs
identifier_name
hwacha.py
import numpy as np import ctypes as ct import ast from ctree.jit import LazySpecializedFunction, ConcreteSpecializedFunction from ctree.transformations import PyBasicConversions from ctree.transforms.declaration_filler import DeclarationFiller from ctree.c.nodes import CFile import ctree.c.nodes as C from ctree.nodes ...
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
import numpy as np import ctypes as ct import ast from ctree.jit import LazySpecializedFunction, ConcreteSpecializedFunction from ctree.transformations import PyBasicConversions from ctree.transforms.declaration_filler import DeclarationFiller from ctree.c.nodes import CFile import ctree.c.nodes as C from ctree.nodes ...
(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
import numpy as np import ctypes as ct import ast from ctree.jit import LazySpecializedFunction, ConcreteSpecializedFunction from ctree.transformations import PyBasicConversions from ctree.transforms.declaration_filler import DeclarationFiller from ctree.c.nodes import CFile import ctree.c.nodes as C from ctree.nodes ...
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
import numpy as np import ctypes as ct import ast from ctree.jit import LazySpecializedFunction, ConcreteSpecializedFunction from ctree.transformations import PyBasicConversions from ctree.transforms.declaration_filler import DeclarationFiller from ctree.c.nodes import CFile import ctree.c.nodes as C from ctree.nodes ...
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
//! `hull` is Theseus's shell for basic interactive systems operations. //! //! Just as the hull is the outermost layer or "shell" of a boat or ship, //! this crate `hull` is the shell of the "Ship of Theseus" (this OS). //! //! Functionally, this is similar to bash, zsh, fish, etc. //! //! This shell will eventually s...
} struct AppDisciplineGuard { discipline: Arc<LineDiscipline>, } impl Drop for AppDisciplineGuard { fn drop(&mut self) { self.discipline.set_raw(); } } #[cfg(test)] mod tests { use super::*; use alloc::vec; #[test] fn test_split_pipes() { assert_eq!( split_pi...
{ 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
//! `hull` is Theseus's shell for basic interactive systems operations. //! //! Just as the hull is the outermost layer or "shell" of a boat or ship, //! this crate `hull` is the shell of the "Ship of Theseus" (this OS). //! //! Functionally, this is similar to bash, zsh, fish, etc. //! //! This shell will eventually s...
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
//! `hull` is Theseus's shell for basic interactive systems operations. //! //! Just as the hull is the outermost layer or "shell" of a boat or ship, //! this crate `hull` is the shell of the "Ship of Theseus" (this OS). //! //! Functionally, this is similar to bash, zsh, fish, etc. //! //! This shell will eventually s...
(&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
import * as d3 from 'd3'; var L = require('leaflet'); import * as topojson from 'topojson'; /** * Leaflet Chart * Creates a map using Leaflet.js */ export default function (config, helper) { var Leaflet = Object.create(helper); Leaflet.init = function (config) { const vm = this; vm._config = config ? c...
function enterLayer(layer) { tip.show(layer, d3.select(layer._path).node()); } function leaveLayer(layer) { tip.hide(layer); } /** * Draw Legend */ if (typeof vm._config.legend === 'function') { vm._config.legend.call(this, vm._nodes); } Leaflet.drawColor...
{ 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
import * as d3 from 'd3'; var L = require('leaflet'); import * as topojson from 'topojson'; /** * Leaflet Chart * Creates a map using Leaflet.js */ export default function (config, helper) { var Leaflet = Object.create(helper); Leaflet.init = function (config) { const vm = this; vm._config = config ? c...
(layer) { 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({ ...
handleLayer
identifier_name
leaflet.js
import * as d3 from 'd3'; var L = require('leaflet'); import * as topojson from 'topojson'; /** * Leaflet Chart * Creates a map using Leaflet.js */ export default function (config, helper) { var Leaflet = Object.create(helper); Leaflet.init = function (config) { const vm = this; vm._config = config ? c...
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
import * as d3 from 'd3'; var L = require('leaflet'); import * as topojson from 'topojson'; /** * Leaflet Chart * Creates a map using Leaflet.js */ export default function (config, helper) { var Leaflet = Object.create(helper); Leaflet.init = function (config) { const vm = this; vm._config = config ? c...
}, }); 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
import random import os import numpy as np import torch import torch.utils.data as data_utils import torch.optim as optim import torch.nn as nn import torch.nn.functional as F from sklearn.svm import SVC from torch.nn import GRU, Embedding, Linear from util import Embedder from tools import balance from tqdm import tqd...
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
import random import os import numpy as np import torch import torch.utils.data as data_utils import torch.optim as optim import torch.nn as nn import torch.nn.functional as F from sklearn.svm import SVC from torch.nn import GRU, Embedding, Linear from util import Embedder from tools import balance from tqdm import tqd...
(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
import random import os import numpy as np import torch import torch.utils.data as data_utils import torch.optim as optim import torch.nn as nn import torch.nn.functional as F from sklearn.svm import SVC from torch.nn import GRU, Embedding, Linear from util import Embedder from tools import balance from tqdm import tqd...
if(use_dp): protected_target_X = torch.FloatTensor(protected_target_X) preds = util_clf.predict(protected_target_X) protected_util_acc = np.mean(preds == target_util_y) if(VERBOSE): print("TRAINING SET SIZE: {}".format(len(Y))) print("EMBEDDINGS FROM TARGET...
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
import random import os import numpy as np import torch import torch.utils.data as data_utils import torch.optim as optim import torch.nn as nn import torch.nn.functional as F from sklearn.svm import SVC from torch.nn import GRU, Embedding, Linear from util import Embedder from tools import balance from tqdm import tqd...
acc, protected_acc = 0.0, 0.0 util_acc, protected_util_acc = 0.0, 0.0 if CLS == 'MLP': print("Histogram of the Target Y: {}".format(np.histogram(Target_Y))) clf = NonLinearClassifier(key, EMB_DIM_TABLE[ARCH], HIDDEN_DIM) clf.cuda() clf.fit(X, Y) # assume the existen...
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
/// How our data look? // Main logs contains when bot started to run, what is total log amount // Keywords logs contains indivitual keyword with their own logs use serde::{Deserialize, Serialize}; use serde_json::Value; use std::collections::HashMap; use std::sync::Arc; use tokio::sync::RwLock; type Account = String...
// println!("Backup done"); let mut no_of_main_log_cleared = 0; { if count == 0 { let ms = &mut statistics.main_stats; ms.error_counts = 0; ms.log_counts = 0; ms.no_api_calls = 0; ms.no_internal_api_calls = 0; } let main_...
random_line_split
models.rs
/// How our data look? // Main logs contains when bot started to run, what is total log amount // Keywords logs contains indivitual keyword with their own logs use serde::{Deserialize, Serialize}; use serde_json::Value; use std::collections::HashMap; use std::sync::Arc; use tokio::sync::RwLock; type Account = String...
} } #[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
/// How our data look? // Main logs contains when bot started to run, what is total log amount // Keywords logs contains indivitual keyword with their own logs use serde::{Deserialize, Serialize}; use serde_json::Value; use std::collections::HashMap; use std::sync::Arc; use tokio::sync::RwLock; type Account = String...
{ 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
#!/usr/bin/python3 # # tsviz # # a command-line utility to help visualize TypeScript class-dependencies and # graphs. # from argparse import ArgumentParser import re import os debug_output = False solution_path = "." allow_loose_module_match = False module_import_declaration = re.compile("import .* from [\"'](.*)[\...
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
#!/usr/bin/python3 # # tsviz # # a command-line utility to help visualize TypeScript class-dependencies and # graphs. # from argparse import ArgumentParser import re import os debug_output = False solution_path = "." allow_loose_module_match = False module_import_declaration = re.compile("import .* from [\"'](.*)[\...
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
#!/usr/bin/python3 # # tsviz # # a command-line utility to help visualize TypeScript class-dependencies and # graphs. # from argparse import ArgumentParser import re import os debug_output = False solution_path = "." allow_loose_module_match = False module_import_declaration = re.compile("import .* from [\"'](.*)[\...
(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
#!/usr/bin/python3 # # tsviz # # a command-line utility to help visualize TypeScript class-dependencies and # graphs. # from argparse import ArgumentParser import re import os debug_output = False solution_path = "." allow_loose_module_match = False module_import_declaration = re.compile("import .* from [\"'](.*)[\...
def get_module_by_filename(filename, modules): for module in modules: if module.filename == filename: return module return None def get_module_by_loose_name(name, modules): basename = os.path.basename(name).lower() for module in modules: if os.path.basename(module.filena...
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
use std::ops::Deref; use std::path::PathBuf; use serde::Deserialize; use structopt::StructOpt; use tmux_interface::{AttachSession, NewSession, NewWindow, SelectWindow, SendKeys, SplitWindow, TmuxInterface}; const ORIGINAL_WINDOW_NAME: &str = "__DEFAULT__"; #[derive(Debug, Deserialize)] struct Setup { file: Option<S...
} 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
use std::ops::Deref; use std::path::PathBuf; use serde::Deserialize; use structopt::StructOpt; use tmux_interface::{AttachSession, NewSession, NewWindow, SelectWindow, SendKeys, SplitWindow, TmuxInterface}; const ORIGINAL_WINDOW_NAME: &str = "__DEFAULT__"; #[derive(Debug, Deserialize)] struct Setup { file: Option<S...
} } None } #[derive(Debug, PartialEq, Copy, Clone)] enum Ordinal { North, South, East, West, } impl Ordinal { fn opposite(&self) -> Ordinal { match self { Ordinal::North => Ordinal::South, Ordinal::South => Ordinal::North, Ordinal::East => Ordinal::West, Ordinal::West => Ordinal::East, } }...
{ return Some((left_index, right_index, *ordinal)); }
conditional_block
main.rs
use std::ops::Deref; use std::path::PathBuf; use serde::Deserialize; use structopt::StructOpt; use tmux_interface::{AttachSession, NewSession, NewWindow, SelectWindow, SendKeys, SplitWindow, TmuxInterface}; const ORIGINAL_WINDOW_NAME: &str = "__DEFAULT__"; #[derive(Debug, Deserialize)] struct Setup { file: Option<S...
{ x: u8, y: u8, length: u8, } fn determine_rectangles(layout: &str) -> Vec<Rect> { let (width, height, chars) = sanitise_input(layout); macro_rules! point { ($index:ident) => {{ let x = $index % width; let y = $index / width; (x, y) }}; } let mut index = 0usize; let mut rects = vec![]; let ...
Edge
identifier_name
rezepte.ts
import { Component } from '@angular/core'; import { AlertController } from 'ionic-angular'; import { NavController, NavParams } from 'ionic-angular'; import { Rezeptansicht } from '../rezeptansicht/rezeptansicht';
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
import { Component } from '@angular/core'; import { AlertController } from 'ionic-angular'; import { NavController, NavParams } from 'ionic-angular'; import { Rezeptansicht } from '../rezeptansicht/rezeptansicht'; @Component({ selector: 'page-rezepte', templateUrl: 'rezepte.html' }) export class Rezepte { recipe...
: 'Deine Punktzahl ist ' + this.score, message: 'Du benötigst ' + this.calculateMissingPoints() + ' Punkte für das nächste Level.', buttons: ['OK'] }); alert.present(); } calculateMissingPoints(){ if (this.score < this.level2){ this.missingPoints = this.level2 - this.score; } else...
howScore(){ let alert = this.alertCtrl.create({ title
identifier_body
rezepte.ts
import { Component } from '@angular/core'; import { AlertController } from 'ionic-angular'; import { NavController, NavParams } from 'ionic-angular'; import { Rezeptansicht } from '../rezeptansicht/rezeptansicht'; @Component({ selector: 'page-rezepte', templateUrl: 'rezepte.html' }) export class Rezepte { recipe...
tzahl ist ' + this.score, message: 'Du benötigst ' + this.calculateMissingPoints() + ' Punkte für das nächste Level.', buttons: ['OK'] }); alert.present(); } calculateMissingPoints(){ if (this.score < this.level2){ this.missingPoints = this.level2 - this.score; } else if (this.sco...
eine Punk
identifier_name
rezepte.ts
import { Component } from '@angular/core'; import { AlertController } from 'ionic-angular'; import { NavController, NavParams } from 'ionic-angular'; import { Rezeptansicht } from '../rezeptansicht/rezeptansicht'; @Component({ selector: 'page-rezepte', templateUrl: 'rezepte.html' }) export class Rezepte { recipe...
ptansicht, {recipe}); } }
ecipe) { this.navCtrl.push(Reze
conditional_block
RecipeDetail.js
import React, { Component } from 'react'; import { Carousel } from 'react-responsive-carousel'; import 'react-responsive-carousel/lib/styles/carousel.min.css'; import Comments from '../Comments'; import Countdown from 'react-countdown-now'; import { Link } from 'react-router/lib'; import LocalizedStrings from 'react-lo...
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
import React, { Component } from 'react'; import { Carousel } from 'react-responsive-carousel'; import 'react-responsive-carousel/lib/styles/carousel.min.css'; import Comments from '../Comments'; import Countdown from 'react-countdown-now'; import { Link } from 'react-router/lib'; import LocalizedStrings from 'react-lo...
}) .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
import React, { Component } from 'react'; import { Carousel } from 'react-responsive-carousel'; import 'react-responsive-carousel/lib/styles/carousel.min.css'; import Comments from '../Comments'; import Countdown from 'react-countdown-now'; import { Link } from 'react-router/lib'; import LocalizedStrings from 'react-lo...
(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
var gl; var targetVertices=[]; var targetUVs = []; //Ball Arrays var ballVertices=[]; var ballUVs = []; var velocities = []; //Ball constants var maxBalls = 500; var radius = 0.2; var ballIndex = 0; var maxZ = 20; var minY = -50; var initVel = 1.1; var gravity = vec3(0, -0.01, 0); var powerScale = 0.01; var pointsA...
; function render() { gl.clear( gl.COLOR_BUFFER_BIT ); //Draw each ball for(var i = 0; i < ballIndex; i++){ gl.drawArrays( gl.TRIANGLE_FAN, i * (pointsAroundCircle + 2), pointsAroundCircle + 2); } //Draw each target for(var i = 0; i < maxNumTargets; i++){ gl.drawArrays(gl.TRIANGLE_...
{ 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
var gl; var targetVertices=[]; var targetUVs = []; //Ball Arrays var ballVertices=[]; var ballUVs = []; var velocities = []; //Ball constants var maxBalls = 500; var radius = 0.2; var ballIndex = 0; var maxZ = 20; var minY = -50; var initVel = 1.1; var gravity = vec3(0, -0.01, 0); var powerScale = 0.01; var pointsA...
(gl, url) { const texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); //Initialize texture with one blue pixel const level = 0; const internalFormat = gl.RGBA; const width = 1; const height = 1; const border = 0; const srcFormat = gl.RGBA; const srcType = gl.UNSIGNED_BYTE; co...
loadTexture
identifier_name
shoot_ball.js
var gl; var targetVertices=[]; var targetUVs = []; //Ball Arrays var ballVertices=[]; var ballUVs = []; var velocities = []; //Ball constants var maxBalls = 500; var radius = 0.2; var ballIndex = 0; var maxZ = 20; var minY = -50; var initVel = 1.1; var gravity = vec3(0, -0.01, 0); var powerScale = 0.01; var pointsA...
} //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
var gl; var targetVertices=[]; var targetUVs = []; //Ball Arrays var ballVertices=[]; var ballUVs = []; var velocities = []; //Ball constants var maxBalls = 500; var radius = 0.2; var ballIndex = 0; var maxZ = 20; var minY = -50; var initVel = 1.1; var gravity = vec3(0, -0.01, 0); var powerScale = 0.01; var pointsAr...
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
#![allow(clippy::excessive_precision)] use wide::*; use bytemuck::*; #[test] fn unpack_modify_and_repack_rgba_values() { let mask = u32x4::from(0xFF); // let input = u32x4::from([0xFF0000FF, 0x00FF00FF, 0x0000FFFF, 0x000000FF]); // unpack let r_actual = cast::<_, i32x4>(input >> 24).round_float(); let g...
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
#![allow(clippy::excessive_precision)] use wide::*; use bytemuck::*; #[test] fn unpack_modify_and_repack_rgba_values() { let mask = u32x4::from(0xFF); // let input = u32x4::from([0xFF0000FF, 0x00FF00FF, 0x0000FFFF, 0x000000FF]); // unpack let r_actual = cast::<_, i32x4>(input >> 24).round_float(); let g...
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
#![allow(clippy::excessive_precision)] use wide::*; use bytemuck::*; #[test] fn unpack_modify_and_repack_rgba_values() { let mask = u32x4::from(0xFF); // let input = u32x4::from([0xFF0000FF, 0x00FF00FF, 0x0000FFFF, 0x000000FF]); // unpack let r_actual = cast::<_, i32x4>(input >> 24).round_float(); let g...
(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
module.exports = (function(win, doc) { var $$ = win.mvue, _CACHE = $$._CACHE_; /** * 根据传入的页面名字,返回页面组件别名 */ function _makeViewName(name, tag) { var ret = "ma-"+name; ret = ret.replace(/[\-|\\|\/]/g, "-"); return tag ? "<"+ret+"></"+ret+">" : ret; } /** * 参数值...
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
module.exports = (function(win, doc) { var $$ = win.mvue, _CACHE = $$._CACHE_; /** * 根据传入的页面名字,返回页面组件别名 */ function _makeViewName(name, tag) { var ret = "ma-"+name; ret = ret.replace(/[\-|\\|\/]/g, "-"); return tag ? "<"+ret+"></"+ret+">" : ret; } /** * 参数值...
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
module.exports = (function(win, doc) { var $$ = win.mvue, _CACHE = $$._CACHE_; /** * 根据传入的页面名字,返回页面组件别名 */ function _makeViewName(name, tag) { v
"+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
module.exports = (function(win, doc) { var $$ = win.mvue, _CACHE = $$._CACHE_; /** * 根据传入的页面名字,返回页面组件别名 */ function _makeViewName(name, tag) { var ret = "ma-"+name;
*/ 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
// Code generated by smithy-go-codegen DO NOT EDIT. package lexruntimeservice import ( "context" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/aws-sdk-go-v2/aws/signer/v4" "github.com/aws/aws-sdk-go-v2/service/lexruntimeservice/types" "github.com/awslabs/smithy-go/middleware" smith...
func newServiceMetadataMiddleware_opPostText(region string) awsmiddleware.RegisterServiceMetadata { return awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, SigningName: "lex", OperationName: "PostText", } }
{ 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
// Code generated by smithy-go-codegen DO NOT EDIT. package lexruntimeservice import ( "context" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/aws-sdk-go-v2/aws/signer/v4" "github.com/aws/aws-sdk-go-v2/service/lexruntimeservice/types" "github.com/awslabs/smithy-go/middleware" smith...
// 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
// Code generated by smithy-go-codegen DO NOT EDIT. package lexruntimeservice import ( "context" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/aws-sdk-go-v2/aws/signer/v4" "github.com/aws/aws-sdk-go-v2/service/lexruntimeservice/types" "github.com/awslabs/smithy-go/middleware" smith...
(region string) awsmiddleware.RegisterServiceMetadata { return awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, SigningName: "lex", OperationName: "PostText", } }
newServiceMetadataMiddleware_opPostText
identifier_name
api_op_PostText.go
// Code generated by smithy-go-codegen DO NOT EDIT. package lexruntimeservice import ( "context" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/aws-sdk-go-v2/aws/signer/v4" "github.com/aws/aws-sdk-go-v2/service/lexruntimeservice/types" "github.com/awslabs/smithy-go/middleware" smith...
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
#!/usr/bin/env python #-*- coding: utf-8 -*- """ __author__ = "Kevin Bedin, Clement Bichat, Aurelien Grenier" __version__ = "1.0.1" __date__ = "2020-01-20" __status__ = "Development" """ """ Contexte : - Ulysse Unmaned Surface Vehicule - Utilisation avec ROS et le package Mavros Objectif : ...
""" 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
#!/usr/bin/env python #-*- coding: utf-8 -*- """ __author__ = "Kevin Bedin, Clement Bichat, Aurelien Grenier" __version__ = "1.0.1" __date__ = "2020-01-20" __status__ = "Development" """ """ Contexte : - Ulysse Unmaned Surface Vehicule - Utilisation avec ROS et le package Mavros Objectif : ...
: 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
#!/usr/bin/env python #-*- coding: utf-8 -*- """ __author__ = "Kevin Bedin, Clement Bichat, Aurelien Grenier" __version__ = "1.0.1" __date__ = "2020-01-20" __status__ = "Development" """ """ Contexte : - Ulysse Unmaned Surface Vehicule - Utilisation avec ROS et le package Mavros Objectif : ...
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
#!/usr/bin/env python #-*- coding: utf-8 -*- """ __author__ = "Kevin Bedin, Clement Bichat, Aurelien Grenier" __version__ = "1.0.1" __date__ = "2020-01-20" __status__ = "Development" """ """ Contexte : - Ulysse Unmaned Surface Vehicule - Utilisation avec ROS et le package Mavros Objectif : ...
: """ 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
package lfs import ( "context" "io/ioutil" "log" "os" "os/exec" "path/filepath" "strings" "time" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/network" "github.com/docker/docker/client" "github.com/docker/go-connections/nat" git "...
func PrintDiff(path, id string) (string, error) { path, err := filepath.Abs(path) if err != nil { return "", errors.Wrap(err, "Could not get absolute path of output directory") } repo, _, err := openRepository(path) if err != nil { return "", errors.Wrap(err, "Could not open repository") } index, err := ...
{ 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
package lfs import ( "context" "io/ioutil" "log" "os" "os/exec" "path/filepath" "strings" "time" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/network" "github.com/docker/docker/client" "github.com/docker/go-connections/nat" git "...
(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
package lfs import ( "context" "io/ioutil" "log" "os" "os/exec" "path/filepath" "strings" "time" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/network" "github.com/docker/docker/client" "github.com/docker/go-connections/nat" git "...
} 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
package lfs import ( "context" "io/ioutil" "log" "os" "os/exec" "path/filepath" "strings" "time" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/network" "github.com/docker/docker/client" "github.com/docker/go-connections/nat" git "...
} repo, _, err := openRepository(path) if err != nil { return errors.Wrap(err, "Could not open repository") } oid, err := git.NewOid(id) if err != nil { return errors.Wrap(err, "Could not create oid for id "+id) } commit, err := repo.LookupCommit(oid) if err != nil { return errors.Wrap(err, "Could not...
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
package main import ( "encoding/json" "fmt" "io" "os" "os/exec" "path/filepath" "strconv" "testing" gofrogcmd "github.com/jfrog/gofrog/io" "github.com/jfrog/jfrog-cli-go/artifactory/commands/pip" piputils "github.com/jfrog/jfrog-cli-go/artifactory/utils/pip" "github.com/jfrog/jfrog-cli-go/inttestutils" "...
{"setuppy", "setuppyproject", "setuppy", "jfrog-python-example", []string{".", "--no-cache-dir", "--force-reinstall"}, 3, true}, {"setuppy-verbose", "setuppyproject", "setuppy-verbose", "jfrog-python-example", []string{".", "--no-cache-dir", "--force-reinstall", "-v"}, 3, true}, {"setuppy-with-module", "setuppypr...
moduleId string args []string expectedDependencies int cleanAfterExecution bool }{
random_line_split
pip_test.go
package main import ( "encoding/json" "fmt" "io" "os" "os/exec" "path/filepath" "strconv" "testing" gofrogcmd "github.com/jfrog/gofrog/io" "github.com/jfrog/jfrog-cli-go/artifactory/commands/pip" piputils "github.com/jfrog/jfrog-cli-go/artifactory/utils/pip" "github.com/jfrog/jfrog-cli-go/inttestutils" "...
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
package main import ( "encoding/json" "fmt" "io" "os" "os/exec" "path/filepath" "strconv" "testing" gofrogcmd "github.com/jfrog/gofrog/io" "github.com/jfrog/jfrog-cli-go/artifactory/commands/pip" piputils "github.com/jfrog/jfrog-cli-go/artifactory/utils/pip" "github.com/jfrog/jfrog-cli-go/inttestutils" "...
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
package main import ( "encoding/json" "fmt" "io" "os" "os/exec" "path/filepath" "strconv" "testing" gofrogcmd "github.com/jfrog/gofrog/io" "github.com/jfrog/jfrog-cli-go/artifactory/commands/pip" piputils "github.com/jfrog/jfrog-cli-go/artifactory/utils/pip" "github.com/jfrog/jfrog-cli-go/inttestutils" "...
() 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
package lightning import ( "encoding/json" "fmt" "log" "time" "github.com/tidwall/gjson" ) var InvoiceListeningTimeout = time.Minute * 150 var WaitSendPayTimeout = time.Hour * 24 var WaitPaymentMaxAttempts = 60 type Client struct { Path string PaymentHandler func(gjson.Result) LastInvoiceIndex...
type Try struct { Route interface{} `json:"route"` Error *ErrorCommand `json:"error"` Success bool `json:"success"` }
{ 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
package lightning import ( "encoding/json" "fmt" "log" "time" "github.com/tidwall/gjson" ) var InvoiceListeningTimeout = time.Minute * 150 var WaitSendPayTimeout = time.Hour * 24 var WaitPaymentMaxAttempts = 60 type Client struct { Path string PaymentHandler func(gjson.Result) LastInvoiceIndex...
else { // now we'll get the value of a hop we've just calculated/iterated over nextHintHop := fullNewRoute[r+1] nextmsat = nextHintHop["msatoshi"].(int64) nextdelay = nextHintHop["delay"].(int64) nextHintChannel := fullHint.Array()[h+1] nextpeer = nextHintChannel.Get("pubkey").String() delaydelta = next...
{ // 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
package lightning import ( "encoding/json" "fmt" "log" "time" "github.com/tidwall/gjson" ) var InvoiceListeningTimeout = time.Minute * 150 var WaitSendPayTimeout = time.Hour * 24 var WaitPaymentMaxAttempts = 60 type Client struct { Path string PaymentHandler func(gjson.Result) LastInvoiceIndex...
// 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
package lightning import ( "encoding/json" "fmt" "log" "time" "github.com/tidwall/gjson" ) var InvoiceListeningTimeout = time.Minute * 150 var WaitSendPayTimeout = time.Hour * 24 var WaitPaymentMaxAttempts = 60 type Client struct { Path string PaymentHandler func(gjson.Result) LastInvoiceIndex...
( 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
3 #!/usr/bin/env python # # File: ProgramsTab.py # by @BitK_ # import re import json from functools import partial from java.awt import ( Font, Color, GridBagLayout, GridBagConstraints, Dimension, Desktop, GridLayout, BorderLayout, FlowLayout, ) from java.net import URI from javax.s...
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
3 #!/usr/bin/env python # # File: ProgramsTab.py # by @BitK_ # import re import json from functools import partial from java.awt import ( Font, Color, GridBagLayout, GridBagConstraints, Dimension, Desktop, GridLayout, BorderLayout, FlowLayout, ) from java.net import URI from javax.s...
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
3 #!/usr/bin/env python # # File: ProgramsTab.py # by @BitK_ # import re import json from functools import partial from java.awt import ( Font, Color, GridBagLayout, GridBagConstraints, Dimension, Desktop, GridLayout, BorderLayout, FlowLayout, ) from java.net import URI from javax.s...
(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
3 #!/usr/bin/env python # # File: ProgramsTab.py # by @BitK_ # import re import json from functools import partial from java.awt import ( Font, Color, GridBagLayout, GridBagConstraints, Dimension, Desktop, GridLayout, BorderLayout, FlowLayout, ) from java.net import URI from javax.s...
class TitleBox(JPanel): def __init__(self, program): self.setLayout(BorderLayout()) title = JLabel(program.title) title.setFont(Font("Arial", Font.BOLD, 28)) title.setHorizontalAlignment(JLabel.CENTER) title.setVerticalAlignment(JLabel.CENTER) title.setBorder(creat...
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
// Copyright (c) 2018 Uber Technologies, Inc. // // 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 without limitation the rights // to use, copy, modify, merge...
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
// Copyright (c) 2018 Uber Technologies, Inc. // // 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 without limitation the rights // to use, copy, modify, merge...
// 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
// Copyright (c) 2018 Uber Technologies, Inc. // // 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 without limitation the rights // to use, copy, modify, merge...
( def UnaggregatedClusterNamespaceDefinition, ) (ClusterNamespace, error) { if err := def.Validate(); err != nil { return nil, err } ns := def.NamespaceID // Set namespace to NoFinalize to avoid cloning it in write operations ns.NoFinalize() return &clusterNamespace{ namespaceID: ns, options: ClusterNames...
newUnaggregatedClusterNamespace
identifier_name
cluster.go
// Copyright (c) 2018 Uber Technologies, Inc. // // 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 without limitation the rights // to use, copy, modify, merge...
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
// vi: sw=4 ts=4: /* --------------------------------------------------------------------------- Copyright (c) 2013-2015 AT&T Intellectual Property 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 ...
( 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
// vi: sw=4 ts=4: /* --------------------------------------------------------------------------- Copyright (c) 2013-2015 AT&T Intellectual Property 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 ...
} jstr += " ]" } else { jstr = fmt.Sprintf( `{ "id": %q }`, *s.id ) } if len( s.hosts ) > 0 { jstr += fmt.Sprintf( `, "conn_hosts": [ ` ) sep = "" for k := range s.hosts { if s.hosts[k] == true { vmid := "unknown" if s.hvmid[k] != nil { vmid = *s.hvmid[k] } jstr += fmt.Sprintf( ...
sep = ","
random_line_split
switch.go
// vi: sw=4 ts=4: /* --------------------------------------------------------------------------- Copyright (c) 2013-2015 AT&T Intellectual Property 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 ...
// -------------------- formatting ---------------------------------------------------- /* Generate some useable representation for debugging Deprectated -- use Stringer interface (String()) */ func (s *Switch) To_str( ) ( string ) { return s.String() } /* Generate some useable representation for debugging */ f...
{ 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
// vi: sw=4 ts=4: /* --------------------------------------------------------------------------- Copyright (c) 2013-2015 AT&T Intellectual Property 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 ...
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
package message import ( "fmt" "bytes" "errors" "time" "unsafe" "crypto/sha256" "encoding/binary" "encoding/hex" "dad-go/common" "dad-go/node" ) const ( MSGCMDLEN = 12 CMDOFFSET = 4 CHECKSUMLEN = 4 HASHLEN = 32 // hash length in byte MSGHDRLEN = 24 ) // The Inventory type const ( TXN = 0x01 // Tran...
() ([]byte, error) { var buf bytes.Buffer fmt.Printf("The size of messge is %d in serialization\n", uint32(unsafe.Sizeof(msg))) err := binary.Write(&buf, binary.LittleEndian, msg) if err != nil { return nil, err } return buf.Bytes(), err } func (msg *headersReq) deserialization(p []byte) error { fmt.Print...
serialization
identifier_name