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 |
|---|---|---|---|---|
bert_tagger_trainer.py | BertTagger.from_pretrained(args.bert_config_dir, config=bert_config)
logging.info(str(args.__dict__ if isinstance(args, argparse.ArgumentParser) else args))
self.result_logger = logging.getLogger(__name__)
self.result_logger.setLevel(logging.INFO)
self.loss_func = CrossEntropyLoss()
... |
def test_epoch_end(self, outputs) -> Dict[str, Dict[str, Tensor]]:
avg_loss = torch.stack([x['test_loss'] for x in outputs]).mean()
tensorboard_logs = {'test_loss': avg_loss}
| random_line_split | |
bert_tagger_trainer.py | _argument("--polydecay_ratio", type=float, default=4, help="ratio for polydecay learing rate scheduler.")
parser.add_argument("--do_lowercase", action="store_true", )
parser.add_argument("--data_file_suffix", type=str, default=".char.bmes")
parser.add_argument("--lr_scheulder", type=str, default... | dataset = TruncateDataset(dataset, limit) | conditional_block | |
bert_tagger_trainer.py | _config_dir, use_fast=False, do_lower_case=args.do_lowercase)
self.model = BertTagger.from_pretrained(args.bert_config_dir, config=bert_config)
logging.info(str(args.__dict__ if isinstance(args, argparse.ArgumentParser) else args))
self.result_logger = logging.getLogger(__name__)
self.re... | (self):
"""Prepare optimizer and schedule (linear warmup and decay)"""
no_decay = ["bias", "LayerNorm.weight"]
optimizer_grouped_parameters = [
{
"params": [p for n, p in self.model.named_parameters() if not any(nd in n for nd in no_decay)],
"weight_de... | configure_optimizers | identifier_name |
bert_tagger_trainer.py | _config_dir, use_fast=False, do_lower_case=args.do_lowercase)
self.model = BertTagger.from_pretrained(args.bert_config_dir, config=bert_config)
logging.info(str(args.__dict__ if isinstance(args, argparse.ArgumentParser) else args))
self.result_logger = logging.getLogger(__name__)
self.re... |
def validation_step(self, batch, batch_idx):
output = {}
token_input_ids, token_type_ids, attention_mask, sequence_labels, is_wordpiece_mask = batch
batch_size = token_input_ids.shape[0]
logits = self.model(token_input_ids, token_type_ids=token_type_ids, attention_mask=attention_m... | tf_board_logs = {"lr": self.trainer.optimizers[0].param_groups[0]['lr']}
token_input_ids, token_type_ids, attention_mask, sequence_labels, is_wordpiece_mask = batch
logits = self.model(token_input_ids, token_type_ids=token_type_ids, attention_mask=attention_mask)
loss = self.compute_loss(logits... | identifier_body |
user-order.component.ts |
weightCache: { [key: string]: string } = {}
readonly = false
tablePageIndex = 1
tablePageSize = 5
pageSizeSelectorValues = [5, 10, 20, 30, 40, 50, 100, 200]
defaultCar: CarOrder
popVisible: { [key: string]: boolean } = {}
constructor(
private route: ActivatedRoute,
private location: Location,
... | em.id]) {
if (item.error) {
item.error = false
item.status = '上传完成'
}
return
}
item.status = '待更新'
} else {
item.status = '待上传'
}
item.subject.next(item)
}
itemBlur(item: OrderItem, index: number) {
if (item.weight && !this.readonly) {
... | .toString() === this.weightCache[it | conditional_block |
user-order.component.ts |
weightCache: { [key: string]: string } = {}
readonly = false
tablePageIndex = 1
tablePageSize = 5
pageSizeSelectorValues = [5, 10, 20, 30, 40, 50, 100, 200]
defaultCar: CarOrder
popVisible: { [key: string]: boolean } = {}
constructor(
private route: ActivatedRoute,
private location: Location,
... | nSelect: (selectedCar: CarOrder) => {
this.defaultCar = selectedCar
this.order.car = this.defaultCar.id
this.orderChange()
}
}
})
}
itemSelectCar(item: OrderItem, index: number) {
let carOrder
if (item.car) {
carOrder = { id: item.car }
} else {
... | o | identifier_name |
user-order.component.ts |
weightCache: { [key: string]: string } = {}
readonly = false
tablePageIndex = 1
tablePageSize = 5
pageSizeSelectorValues = [5, 10, 20, 30, 40, 50, 100, 200]
defaultCar: CarOrder
popVisible: { [key: string]: boolean } = {}
constructor(
private route: ActivatedRoute,
private location: Location,
... | ltCar,
onSelect: (selectedCar: CarOrder) => {
this.defaultCar = selectedCar
this.order.car = this.defaultCar.id
this.orderChange()
}
}
})
}
itemSelectCar(item: OrderItem, index: number) {
let carOrder
if (item.car) {
carOrder = { id: item.car }
... | fau | identifier_body |
user-order.component.ts | 0
weightCache: { [key: string]: string } = {}
readonly = false
tablePageIndex = 1
tablePageSize = 5
pageSizeSelectorValues = [5, 10, 20, 30, 40, 50, 100, 200]
defaultCar: CarOrder
popVisible: { [key: string]: boolean } = {}
constructor(
private route: ActivatedRoute,
private location: Location,... | this.allChecked = allChecked
this.indeterminate = (!allChecked) && (!allUnChecked)
this.checkedItems = this.values.filter(value => value.checked)
this.checkedNumber = this.checkedItems.length
}
checkAll(value) {
if (value) {
this.values.forEach(item => {
item.checked = true
}... | random_line_split | |
app.js | 1];
last.lesson = info.lesson;
} else if (info.sublesson != "" && info.sublesson != last.sublesson) {
counters[2] = counters[2] + 1;
counters[3] = -1;
obj.sublesson = counters[2];
last.sublesson = info.sublesson;
} else if (info.subsublesson != "" && info.subsublesson != last.subsublesson) {
counters[3] =... | {
for (var i = 0; i < toc.length; i++) {
var entry = toc[i];
if (entry.video && entry.video.indexOf(file) != -1) {
return {
title: entry.desc,
index: i
}
}
}
} | conditional_block | |
app.js | deleteFolderRecursive(curPath);
} else { // delete file
fs.unlinkSync(curPath);
}
});
fs.rmdirSync(path);
}
}
function makeAllPaths (dir) |
function doConversion (options) {
options.timestamp = Date.now();
options.idx = lunr(function () {
this.field('title');
this.field('body');
});
var input = fs.readFileSync(options.path, "utf8");
var parseOptions = { delimiter: "\t", quote: "" };
parse(input, parseOptions, function(err, output) {
if (!e... | {
var paths = dir.split(path.sep);
var curPath = "";
for (var i = 0; i < paths.length; i++) {
curPath += paths[i] + path.sep;
try {
fs.accessSync(curPath, fs.W_OK);
} catch (err) {
fs.mkdirSync(curPath);
}
}
} | identifier_body |
app.js | .lesson;
} else if (info.sublesson != "" && info.sublesson != last.sublesson) {
counters[2] = counters[2] + 1;
counters[3] = -1;
obj.sublesson = counters[2];
last.sublesson = info.sublesson;
} else if (info.subsublesson != "" && info.subsublesson != last.subsublesson) {
counters[3] = counters[3] + 1;
obj.... | includeSearch | identifier_name | |
app.js | j++) {
if (curDepth[j] != -1 && curDepth[j] != undefined) {
if (obj.depth != "") obj.depth += ",";
obj.depth += curDepth[j];
}
}
lastPart = obj.part;
lastLesson = obj.lesson;
lastSublesson = obj.sublesson;
lastSubsublesson = obj.subsublesson;
lastInfoLesson = info.lesson;
lastDepth = curDe... | var transcriptFilename = path.basename(newFilename, path.extname(newFilename)) + ".dfxp"; | random_line_split | |
retransmit_stage.rs | )
.num_peers();
let stats = std::mem::replace(
self,
Self {
since: Some(Instant::now()),
..Self::default()
},
);
datapoint_info!("retransmit-num_nodes", ("count", num_peers, i64));
datapoint_info!(
... |
true
} else {
false
}
}
fn maybe_reset_shreds_received_cache(
shreds_received: &Mutex<ShredFilterAndHasher>,
hasher_reset_ts: &mut Instant,
) {
const UPDATE_INTERVAL: Duration = Duration::from_secs(1);
if hasher_reset_ts.elapsed() >= UPDATE_INTERVAL {
*hasher_reset_ts =... | {
*first_shreds_received_locked =
first_shreds_received_locked.split_off(&(root_bank.slot() + 1));
} | conditional_block |
retransmit_stage.rs | _info)
.num_peers();
let stats = std::mem::replace(
self,
Self {
since: Some(Instant::now()),
..Self::default()
},
);
datapoint_info!("retransmit-num_nodes", ("count", num_peers, i64));
datapoint_info!(
... | (
shred_slot: Slot,
first_shreds_received: &Mutex<BTreeSet<Slot>>,
root_bank: &Bank,
) -> bool {
if shred_slot <= root_bank.slot() {
return false;
}
let mut first_shreds_received_locked = first_shreds_received.lock().unwrap();
if first_shreds_received_locked.insert(shred_slot) {
... | check_if_first_shred_received | identifier_name |
retransmit_stage.rs | _info)
.num_peers();
let stats = std::mem::replace(
self,
Self {
since: Some(Instant::now()),
..Self::default()
},
);
datapoint_info!("retransmit-num_nodes", ("count", num_peers, i64));
datapoint_info!(
... | sockets: &[UdpSocket],
stats: &mut RetransmitStats,
cluster_nodes_cache: &ClusterNodesCache<RetransmitStage>,
hasher_reset_ts: &mut Instant,
shreds_received: &Mutex<ShredFilterAndHasher>,
max_slots: &MaxSlots,
first_shreds_received: &Mutex<BTreeSet<Slot>>,
rpc_subscriptions: Option<&RpcS... | thread_pool: &ThreadPool,
bank_forks: &RwLock<BankForks>,
leader_schedule_cache: &LeaderScheduleCache,
cluster_info: &ClusterInfo,
shreds_receiver: &Receiver<Vec<Shred>>, | random_line_split |
eng.ts | an issue',
edit: 'Purpose an edit'
},
form: {
title: 'Report an issue',
subtitle: 'We do our best to have a high-quality database, but sometimes some issues are there. Thanks for help!',
type: {
label: 'Problem type',
time: 'Lyrics not synchronised',
quality: 'Low quality video'
... | placeholder: 'LoveLiveFan93'
},
password: {
header: 'Change password',
label: 'Password',
placeholder: 'EnVraiJePréfèreIdolM@ster'
| nickname: {
label: 'Nickname', | random_line_split |
quadstore.go | call Ping."
// Source: http://golang.org/pkg/database/sql/#Open
if err := conn.Ping(); err != nil {
clog.Errorf("Couldn't open database at %s: %#v", addr, err)
return nil, err
}
return conn, nil
}
var nodesColumns = []string{
"hash",
"value",
"value_string",
"datatype",
"language",
"iri",
"bnode",
"va... | func (qs *QuadStore) NameOf(v graph.Value) quad.Value {
if v == nil {
if clog.V(2) { | random_line_split | |
quadstore.go | err = pquads.MarshalValue(q.Subject)
if err != nil {
return
}
p, err = pquads.MarshalValue(q.Predicate)
if err != nil {
return
}
o, err = pquads.MarshalValue(q.Object)
if err != nil {
return
}
l, err = pquads.MarshalValue(q.Label)
if err != nil {
return
}
return
}
func escapeNullByte(s string) str... | sizeForIterator | identifier_name | |
quadstore.go | lru.New(1024)
// Skip size checking by default.
qs.noSizes = true
if localOptOk {
if localOpt {
qs.noSizes = false
}
}
qs.useEstimates, _, err = options.BoolKey("use_estimates")
if err != nil {
return nil, err
}
return &qs, nil
}
func marshalQuadDirections(q quad.Quad) (s, p, o, l []byte, err error... | {
if err != sql.ErrNoRows {
clog.Errorf("Couldn't execute horizon: %v", err)
}
return graph.NewSequentialKey(0)
} | conditional_block | |
quadstore.go | Opt {
qs.noSizes = false
}
}
qs.useEstimates, _, err = options.BoolKey("use_estimates")
if err != nil {
return nil, err
}
return &qs, nil
}
func marshalQuadDirections(q quad.Quad) (s, p, o, l []byte, err error) {
s, err = pquads.MarshalValue(q.Subject)
if err != nil {
return
}
p, err = pquads.Marsha... | {
return iterator.NewFixed(iterator.Identity)
} | identifier_body | |
tbs.rs | BS {
fn as_ref(&self) -> &[u8] {
self.0.as_ref()
}
}
/// Returns the to-be-signed serialization of the given message.
pub fn message_tbs<M: BinEncodable>(message: &M, pre_sig0: &SIG) -> ProtoResult<TBS> {
// TODO: should perform the serialization and sign block by block to reduce the max memory
... | (
name: &Name,
dns_class: DNSClass,
sig: &SIG,
records: &[Record],
) -> ProtoResult<TBS> {
rrset_tbs(
name,
dns_class,
sig.num_labels(),
sig.type_covered(),
sig.algorithm(),
sig.original_ttl(),
sig.sig_expiration(),
sig.sig_inception(),... | rrset_tbs_with_sig | identifier_name |
tbs.rs | BS {
fn as_ref(&self) -> &[u8] {
self.0.as_ref()
}
}
/// Returns the to-be-signed serialization of the given message.
pub fn message_tbs<M: BinEncodable>(message: &M, pre_sig0: &SIG) -> ProtoResult<TBS> {
// TODO: should perform the serialization and sign block by block to reduce the max memory
... | let mut buf: Vec<u8> = Vec::new();
{
let mut encoder: BinEncoder<'_> = BinEncoder::new(&mut buf);
encoder.set_canonical_names(true);
// signed_data = RRSIG_RDATA | RR(1) | RR(2)... where
//
// "|" denotes concatenation
//
// ... | {
// TODO: change this to a BTreeSet so that it's preordered, no sort necessary
let mut rrset: Vec<&Record> = Vec::new();
// collect only the records for this rrset
for record in records {
if dns_class == record.dns_class()
&& type_covered == record.rr_type()
&& name == ... | identifier_body |
tbs.rs | TBS {
fn as_ref(&self) -> &[u8] {
self.0.as_ref()
}
}
/// Returns the to-be-signed serialization of the given message.
pub fn message_tbs<M: BinEncodable>(message: &M, pre_sig0: &SIG) -> ProtoResult<TBS> {
// TODO: should perform the serialization and sign block by block to reduce the max memory
... | {
let mut rdata_encoder = BinEncoder::new(&mut rdata_buf);
rdata_encoder.set_canonical_names(true);
if let Some(rdata) = record.data() {
assert!(rdata.emit(&mut rdata_encoder).is_ok());
}
}
assert!(en... | random_line_split | |
tbs.rs | _capacity(512);
let mut buf2: Vec<u8> = Vec::with_capacity(512);
{
let mut encoder: BinEncoder<'_> = BinEncoder::with_mode(&mut buf, EncodeMode::Normal);
assert!(sig::emit_pre_sig(
&mut encoder,
pre_sig0.type_covered(),
pre_sig0.algorithm(),
pre_s... | {
return Ok(name.clone());
} | conditional_block | |
index.js | .LED_COLORS[led][1];
obj.material.transparent = (obj.material.opacity < 1) ? true : false;
});
};
Drone.prototype._addLEDs = function(group) {
var leds = [];
for (var i = 0; i < 4; i++) {
var led = new this.game.THREE.Mesh(
new this.game.THREE.CubeGeometry(this.size/20, this.size/20, this.size/20),... | anim | identifier_name | |
index.js | });
// start up emitters
self.resume();
// emit navdata
var seq = 0;
setInterval(function() {
if (options.udpNavdataStream._initialized === true) {
options.udpNavdataStream._socket.emit('message', self._emitNavdata(seq++));
}
}, 100);
};
util.inherits(Drone, ardrone.Client);
module.exports... | random_line_split | ||
index.js | led][0];
obj.material.opacity = self.LED_COLORS[led][1];
obj.material.transparent = (obj.material.opacity < 1) ? true : false;
});
};
Drone.prototype._addLEDs = function(group) {
var leds = [];
for (var i = 0; i < 4; i++) {
var led = new this.game.THREE.Mesh(
new this.game.THREE.CubeGeometry(th... | {
if (arguments.length < 3) {
y = x; z = x;
}
item.x = x; item.y = y; item.z = z;
} | identifier_body | |
function.py | out
# =================特征计算===============================================================
# calture_normal_feature: 对于一张图片,计算256尺寸下 center crop特征 (1+2 论文中的baseline)
# calture_pool_feature: 对于一张图片,计算设定尺寸下 以一定步长截取部分图片的特征 然后maxpool
# get_feature_scala_256: 计算整个数据库normal_feature
# get_pool_feature: 计算整个数... | x = i * steplength
y = j * steplength
crop = img[x:x + 224, y:y + 224, :]
im = transformer.preprocess('data', crop)
'''
im = np.transpose(crop, (2, 0, 1))
im = im - mean_data
... | (step_y):
| conditional_block |
function.py | out
# =================特征计算===============================================================
# calture_normal_feature: 对于一张图片,计算256尺寸下 center crop特征 (1+2 论文中的baseline)
# calture_pool_feature: 对于一张图片,计算设定尺寸下 以一定步长截取部分图片的特征 然后maxpool
# get_feature_scala_256: 计算整个数据库normal_feature
# get_pool_feature: 计算整个数... | sql = "SELECT URL FROM " + tbname + " WHERE ID = '%d'" % (i + 1)
cursor.execute(sql)
result = cursor.fetchall()
url = datafloder + result[0][0]
im_ori = cv2.imread(url)
cur_feature = calture_normal_feature(im_ori, caffenet, mean_data)
feature_all.extend(cur_feat... | ====' % (i + 1)
| identifier_name |
function.py |
# =================特征计算===============================================================
# calture_normal_feature: 对于一张图片,计算256尺寸下 center crop特征 (1+2 论文中的baseline)
# calture_pool_feature: 对于一张图片,计算设定尺寸下 以一定步长截取部分图片的特征 然后maxpool
# get_feature_scala_256: 计算整个数据库normal_feature
# get_pool_feature: 计算整个数据库po... | t(rownum / parallelnum)):
print '============current id is :%d ==============' % (i * parallelnum + 1)
sql = "SELECT URL FROM " + tbname + " WHERE ID >= '%d' and ID <= '%d'" % (
i * parallelnum + 1, (i + 1) * parallelnum)
cursor.execute(sql)
result = cursor.fetchall()
... | sor.execute(sql)
result = cursor.fetchall()
url = datafloder + result[0][0]
im_ori = cv2.imread(url)
cur_feature = calture_normal_feature(im_ori, caffenet, mean_data)
feature_all.extend(cur_feature)
feature_all = np.asarray(feature_all, dtype='float32')
print featu... | identifier_body |
function.py |
# =================特征计算===============================================================
# calture_normal_feature: 对于一张图片,计算256尺寸下 center crop特征 (1+2 论文中的baseline)
# calture_pool_feature: 对于一张图片,计算设定尺寸下 以一定步长截取部分图片的特征 然后maxpool
# get_feature_scala_256: 计算整个数据库normal_feature
# get_pool_feature: 计算整个数据库po... | feature_max = []
file = open(file_url, 'r')
count = 0
while True:
current_max = np.zeros((1, 4096))
current_max -= 9999
line = file.readline()
line = line.strip()
if not line:
break
count += 1
print '----------------------cur... |
def get_cam_feature(db, cursor, tbname, file_url, caffenet, datafloder, mean_data, featurename):
transformer = imageTransformer(caffenet, mean_data)
| random_line_split |
vue2jsx.ts | {
constructor(public tagName: string = "", public parentNode: Nullable<ParsedNode> = null) { }
localVariables: string[] = [];
childNodes: ParsedNode[] = [];
startText: string = "";
endText: string = "";
startIf: boolean = false;
condition: string = "";
postProcessor: { (text: string):... | ParsedNode | identifier_name | |
vue2jsx.ts | jsx(html: string) {
var startTagRegex = /^<(!?[-A-Za-z0-9_]+)((?:\s+[\w\-\:\.]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/,
endTagRegex = /^<\/([-A-Za-z0-9_]+)[^>]*>/;
var attrRegex = /\s*[\w\-\:\.]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?/g;
var special: Dictionary<number> =... | pos++;
return pos;
}
| random_line_split | |
vue2jsx.ts | (html: string) {
var startTagRegex = /^<(!?[-A-Za-z0-9_]+)((?:\s+[\w\-\:\.]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/,
endTagRegex = /^<\/([-A-Za-z0-9_]+)[^>]*>/;
var attrRegex = /\s*[\w\-\:\.]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?/g;
var special: Dictionary<number> = { ... | {
while(/\s/.test(jsCode.substr(pos, 1)) && pos < jsCode.length)
pos++;
return pos;
} | identifier_body | |
cme_stats.py | IENCE_KEYWORD = 0, # used the CMR parameters
KEYWORD = 1, # used a free text search inside CMR
BOTH = 2 # Merge the results from science keyword and plain text search
# format a comma separated list into a semi-colon separated list
def format_lot(lot):
lot_str = str(lot)
lot_str = re.sub(r'[\[\]\(\... | for parent_key, value in key_title_ground_truth.items():
pdf_key = value['pdf']
added_pdfs.add(pdf_key)
if pdf_key in features:
# update both csv file and json file
csv = dump_data(pdf_key, features[pdf_key], csv, manually_reviewed=value, title... | csv = "paper, title, mission/instruments, models, manually reviewed, CMR datasets,,,correct, missed, extraneous\n"
# iterate through the manually reviewed papers. Add data into csv and json files via dump_data method | random_line_split |
cme_stats.py | _KEYWORD = 0, # used the CMR parameters
KEYWORD = 1, # used a free text search inside CMR
BOTH = 2 # Merge the results from science keyword and plain text search
# format a comma separated list into a semi-colon separated list
def format_lot(lot):
lot_str = str(lot)
lot_str = re.sub(r'[\[\]\(\)]', ... | (key, features, csv, manually_reviewed=None, title='', running_cme_stats=None, n=1, dataset_search_type=None, include_singles=False):
# extract the platform/ins couples and models from the features
summary_stats = features['summary_stats']
couples = sorted(list(summary_stats['valid_couples'].items()), key=l... | dump_data | identifier_name |
cme_stats.py | _KEYWORD = 0, # used the CMR parameters
KEYWORD = 1, # used a free text search inside CMR
BOTH = 2 # Merge the results from science keyword and plain text search
# format a comma separated list into a semi-colon separated list
def format_lot(lot):
lot_str = str(lot)
lot_str = re.sub(r'[\[\]\(\)]', ... | datasets = inner_value['keyword_search']['dataset']
elif dataset_search_type == CMRSearchType.BOTH:
# merge the two lists together, alternating order
l1 = inner_value['science_keyword_search']['dataset']
l2 = inner_value['keyword_search']['dataset']
i... | summary_stats = features['summary_stats']
couples = sorted(list(summary_stats['valid_couples'].items()), key=lambda x: x[1], reverse=True)
models = sorted(list(summary_stats['models'].items()), key=lambda x: x[1], reverse=True)
title = re.sub(',', '', title)
# write key, title, platform/ins couples, an... | identifier_body |
cme_stats.py | _KEYWORD = 0, # used the CMR parameters
KEYWORD = 1, # used a free text search inside CMR
BOTH = 2 # Merge the results from science keyword and plain text search
# format a comma separated list into a semi-colon separated list
def format_lot(lot):
lot_str = str(lot)
lot_str = re.sub(r'[\[\]\(\)]', ... |
# create semi-colon delineated string with the predicted datasets from CMR and add to csv string
cmr_list = ';'.join(list(cmr_results))
csv += f',{cmr_list}'
# If the paper was manually reviewed update the dictionary containing overall stats about how many datasets were
# correct, missed, and ext... | for predic in single_datasets[:n]:
if predic not in cmr_results:
cmr_results.add(predic) | conditional_block |
mod.rs | result.push(salt);
Ok(result)
}
// Default file path for Account Keys written to isolated persistent storage.
const PERSISTED_ACCOUNT_KEYS_FILEPATH: &'static str = "/data/account_keys.json";
/// Attempts to read and parse the contents of the persistent storage at the provided `path`.
///... | {
let mut list = AccountKeyList::with_capacity_and_keys(MAX_ACCOUNT_KEYS, vec![]);
let max: u8 = MAX_ACCOUNT_KEYS as u8;
for i in 1..max + 1 {
let key = AccountKey::new([i; 16]);
list.save(key.clone());
assert_eq!(list.keys().len(), i as usize);
a... | identifier_body | |
mod.rs | /// A long-lived key that allows the Provider to be recognized as belonging to a certain user
/// account.
#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
pub struct AccountKey(SharedSecret);
impl AccountKey {
pub fn new(bytes: [u8; 16]) -> Self {
Self(SharedSecret::new(bytes))
}
... | }
| random_line_split | |
mod.rs |
Ok(Self(src))
}
}
impl From<ModelId> for [u8; 3] {
fn from(src: ModelId) -> [u8; 3] {
let mut bytes = [0; 3];
bytes[..3].copy_from_slice(&src.0.to_be_bytes()[1..]);
bytes
}
}
/// A key used during the Fast Pair Pairing Procedure.
/// This key is a temporary value that liv... | {
return Err(Error::InvalidModelId(src));
} | conditional_block | |
mod.rs | <AccountKey, ()>,
/// The file path pointing to the isolated persistent storage which saves the Account Keys.
path: path::PathBuf,
/// The number of keys currently saved in the AccountKeyList.
account_key_count: inspect::UintProperty,
}
impl Inspect for &mut AccountKeyList {
fn iattach(self, parent... | invalid_model_id_conversion_is_error | identifier_name | |
utils.rs | color format")?;
Ok(())
}
/// Load a system font.
fn load_font(font_family: &str) -> Vec<u8> {
let font_family_property = system_fonts::FontPropertyBuilder::new()
.family(font_family)
.build();
let (loaded_font, _) =
if let Some((loaded_font, index)) = system_fonts::get(&font_famil... | ;
let loaded_font = load_font(&font_family);
AppConfig {
font_family,
font_size,
loaded_font,
hint_chars,
margin,
text_color,
text_color_alt,
bg_color,
fill,
print_only,
horizontal_align,
vertical_align,
}
}
/... | {
(
value_t!(matches, "horizontal_align", HorizontalAlign).unwrap(),
value_t!(matches, "vertical_align", VerticalAlign).unwrap(),
)
} | conditional_block |
utils.rs | let text_color_alt = parse_color(text_color_alt_unparsed);
let bg_color_unparsed = value_t!(matches, "bg_color", CssColor).unwrap();
let bg_color = parse_color(bg_color_unparsed);
let fill = matches.is_present("fill");
let print_only = matches.is_present("print_only");
let (horizontal_align, vertic... | test_no_intersect | identifier_name | |
utils.rs | .default_value("#666666")
.display_order(50)
.help("Text color alternate (CSS notation)"))
.arg(
Arg::with_name("bg_color")
.long("bgcolor")
.takes_value(true)
.validator(is_valid_color)
.default_value("rgba(30, 30, ... | {
let now = Instant::now();
loop {
if now.elapsed() > timeout {
return Err(format!(
"Couldn't grab keyboard input within {:?}",
now.elapsed()
));
}
let grab_pointer_cookie = xcb::xproto::grab_pointer(
&conn,
... | identifier_body | |
utils.rs | "bottom" => Ok(VerticalAlign::Bottom),
_ => Err(()),
}
}
}
/// Checks whether the provided fontconfig font `f` is valid.
fn is_truetype_font(f: String) -> Result<(), String> {
let v: Vec<_> = f.split(':').collect();
let (family, size) = (v.get(0), v.get(1));
if family.is... | "top" => Ok(VerticalAlign::Top),
"center" => Ok(VerticalAlign::Center), | random_line_split | |
mysql_interactive_worker.rs | 08, 0x00, 0x00, 0x00])
}
fn default_auth_plugin(&self) -> &str {
"mysql_native_password"
}
fn auth_plugin_for_username(&self, _user: &[u8]) -> &str {
"mysql_native_password"
}
fn salt(&self) -> [u8; 20] {
self.salt
}
fn authenticate(
&self,
aut... | }
| random_line_split | |
mysql_interactive_worker.rs | _srv::ParamParser;
use msql_srv::QueryResultWriter;
use msql_srv::StatementMetaWriter;
use rand::RngCore;
use tokio_stream::StreamExt;
use crate::interpreters::InterpreterFactory;
use crate::servers::mysql::writers::DFInitResultWriter;
use crate::servers::mysql::writers::DFQueryResultWriter;
use crate::sessions::Datab... | (&self) -> &str {
"mysql_native_password"
}
fn auth_plugin_for_username(&self, _user: &[u8]) -> &str {
"mysql_native_password"
}
fn salt(&self) -> [u8; 20] {
self.salt
}
fn authenticate(
&self,
auth_plugin: &str,
username: &[u8],
salt: &... | default_auth_plugin | identifier_name |
mysql_interactive_worker.rs | ::ParamParser;
use msql_srv::QueryResultWriter;
use msql_srv::StatementMetaWriter;
use rand::RngCore;
use tokio_stream::StreamExt;
use crate::interpreters::InterpreterFactory;
use crate::servers::mysql::writers::DFInitResultWriter;
use crate::servers::mysql::writers::DFQueryResultWriter;
use crate::sessions::DatabendQ... |
fn encoding_password(
auth_plugin: &str,
salt: &[u8],
input: &[u8],
user_password: &[u8],
) -> Result<Vec<u8>> {
match auth_plugin {
"mysql_native_password" if input.is_empty() => Ok(vec![]),
"mysql_native_password" => {
// SHA1( ... | {
let user_name = &info.user_name;
let address = &info.user_client_address;
let user_manager = self.session.get_user_manager();
let user_info = user_manager.get_user(user_name).await?;
let input = &info.user_password;
let saved = &user_info.password;
let encode_... | identifier_body |
lib.rs | _qual<T, U>(
left: &[T],
left_q: &[U],
right: &[T],
right_q: &[U],
) -> Vec<(T, U)>
where
T: Ord,
T: Clone,
U: Clone,
{
let l = left
.iter()
.zip(left_q.iter())
.map(|(a, b)| (a.clone(), b.clone()));
let r = right
.iter()
.zip(right_q.iter())
... | <T>(v: &[T]) -> bool
where
T: Ord,
{
v.windows(2).all(|w| w[0] <= w[1])
}
/// search a sorted array for insertions positions of another sorted array
/// returned index i satisfies
/// left
/// a\[i-1\] < v <= a\[i\]
/// right
/// a\[i-1\] <= v < a\[i\]
/// <https://numpy.org/doc/stable/reference/generated/nump... | is_sorted | identifier_name |
lib.rs | _with_qual<T, U>(
left: &[T],
left_q: &[U],
right: &[T],
right_q: &[U],
) -> Vec<(T, U)>
where
T: Ord,
T: Clone,
U: Clone,
{
let l = left
.iter()
.zip(left_q.iter())
.map(|(a, b)| (a.clone(), b.clone()));
let r = right
.iter()
.zip(right_q.ite... | let ending_block = aligned_block_pairs.len();
let mut pos_mapping = HashMap::new();
for cur_pos in positions {
pos_mapping.insert(cur_pos, (-1, i64::MAX));
let mut current_block = 0;
for block_index in starting_block..ending_block {
// get the current alignment block
... | );
// find the closest position for every position
let mut starting_block = 0; | random_line_split |
lib.rs | fn search_sorted<T>(a: &[T], v: &[T]) -> Vec<usize>
where
T: Ord,
T: Display,
[T]: Debug,
{
if !is_sorted(v) {
panic!("v is not sorted: {:?}", v);
}
let mut indexes = Vec::with_capacity(v.len());
let mut a_idx = 0;
for cur_v in v {
while a_idx < a.len() {
//... | {
reference_positions.iter().map(|_x| None).collect()
} | conditional_block | |
lib.rs | _qual<T, U>(
left: &[T],
left_q: &[U],
right: &[T],
right_q: &[U],
) -> Vec<(T, U)>
where
T: Ord,
T: Clone,
U: Clone,
{
let l = left
.iter()
.zip(left_q.iter())
.map(|(a, b)| (a.clone(), b.clone()));
let r = right
.iter()
.zip(right_q.iter())
... |
/// get positions on the complimented sequence in the cigar record
pub fn positions_on_complimented_sequence_in_place(
record: &bam::Record,
input_positions: &mut Vec<i64>,
part_of_range: bool,
) {
if !record.is_reverse() {
return;
}
let seq_len = i64::try_from(record.seq_len()).unwrap... | {
// reverse positions if needed
let positions: Vec<i64> = if record.is_reverse() {
let seq_len = i64::try_from(record.seq_len()).unwrap();
input_positions
.iter()
.rev()
.map(|p| seq_len - p - 1)
.collect()
} else {
input_positions.to_... | identifier_body |
chown.rs | reference";
}
static ARG_OWNER: &str = "owner";
static ARG_FILES: &str = "files";
const FTS_COMFOLLOW: u8 = 1;
const FTS_PHYSICAL: u8 = 1 << 1;
const FTS_LOGICAL: u8 = 1 << 2;
fn get_usage() -> String {
format!(
"{0} [OPTION]... [OWNER][:[GROUP]] FILE...\n{0} [OPTION]... --reference=RFILE FILE...",
... | (spec: &str) -> UResult<(Option<u32>, Option<u32>)> {
let args = spec.split_terminator(':').collect::<Vec<_>>();
let usr_only = args.len() == 1 && !args[0].is_empty();
let grp_only = args.len() == 2 && args[0].is_empty();
let usr_grp = args.len() == 2 && !args[0].is_empty() && !args[1].is_empty();
l... | parse_spec | identifier_name |
chown.rs | reference";
}
static ARG_OWNER: &str = "owner";
static ARG_FILES: &str = "files";
const FTS_COMFOLLOW: u8 = 1;
const FTS_PHYSICAL: u8 = 1 << 1;
const FTS_LOGICAL: u8 = 1 << 2;
fn get_usage() -> String {
format!(
"{0} [OPTION]... [OWNER][:[GROUP]] FILE...\n{0} [OPTION]... --reference=RFILE FILE...",
... | )
.arg(
Arg::with_name(options::traverse::NO_TRAVERSE)
.short(options::traverse::NO_TRAVERSE)
.help("do not traverse any symbolic links (default)")
.overrides_with_all(&[options::traverse::TRAVERSE, options::traverse::EVERY]),
)
... | .arg(
Arg::with_name(options::traverse::EVERY)
.short(options::traverse::EVERY)
.help("traverse every symbolic link to a directory encountered")
.overrides_with_all(&[options::traverse::TRAVERSE, options::traverse::NO_TRAVERSE]), | random_line_split |
chown.rs | .uid());
} else {
let (u, g) = parse_spec(owner)?;
dest_uid = u;
dest_gid = g;
}
let executor = Chowner {
bit_flag,
dest_uid,
dest_gid,
verbosity,
recursive,
dereference: derefer != 0,
filter,
preserve_root,
file... | {
if !n.is_empty() {
show_error!("{}", n);
}
0
} | conditional_block | |
bls12_377_scalar.rs | = -|F|^-1 mod 2^64.
const MU: u64 = 725501752471715839;
pub fn from_canonical(c: [u64; 4]) -> Self {
// We compute M(c, R^2) = c * R^2 * R^-1 = c * R.
Self { limbs: Self::montgomery_multiply(c, Self::R2) }
}
pub fn to_canonical(&self) -> [u64; 4] {
// Let x * R = self. We comp... | }
}
impl Field for Bls12377Scalar {
const BITS: usize = 253;
const BYTES: usize = 32;
const ZERO: Self = Self { limbs: [0; 4] };
const ONE: Self = Self { limbs: Self::R };
const TWO: Self = Self { limbs: [17304940830682775525, 10017539527700119523, 14770643272311271387, 570918138838421475] };
... |
Self { limbs: sub(Self::ORDER, self.limbs) }
}
| conditional_block |
bls12_377_scalar.rs | 94542470912991159, 1141836277676842951] };
const FIVE: Self = Self { limbs: [6006113053051977660, 3366551019440832441, 5772352412093595556, 754655161751966990] };
const NEG_ONE: Self = Self { limbs: [10157024534604021774, 16668528035959406606, 5322190058819395602, 387181115924875961] };
const MULTIPLICATIV... | um_bits( | identifier_name | |
bls12_377_scalar.rs | = -|F|^-1 mod 2^64.
const MU: u64 = 725501752471715839;
pub fn from_canonical(c: [u64; 4]) -> Self {
// We compute M(c, R^2) = c * R^2 * R^-1 = c * R.
Self { limbs: Self::montgomery_multiply(c, Self::R2) }
}
pub fn to_canonical(&self) -> [u64; 4] {
// Let x * R = self. We comp... | }
impl Div<Bls12377Scalar> for Bls12377Scalar {
type Output = Self;
fn div(self, rhs: Self) -> Self {
self * rhs.multiplicative_inverse().expect("No inverse")
}
}
impl Neg for Bls12377Scalar {
type Output = Self;
fn neg(self) -> Self {
if self == Self::ZERO {
Self::ZE... | } | random_line_split |
bls12_377_scalar.rs | = -|F|^-1 mod 2^64.
const MU: u64 = 725501752471715839;
pub fn from_canonical(c: [u64; 4]) -> Self {
// We compute M(c, R^2) = c * R^2 * R^-1 = c * R.
Self { limbs: Self::montgomery_multiply(c, Self::R2) }
}
pub fn to_canonical(&self) -> [u64; 4] {
// Let x * R = self. We comp... | }
impl Mul<Self> for Bls12377Scalar {
type Output = Self;
fn mul(self, rhs: Self) -> Self {
Self { limbs: Self::montgomery_multiply(self.limbs, rhs.limbs) }
}
}
impl Div<Bls12377Scalar> for Bls12377Scalar {
type Output = Self;
fn div(self, rhs: Self) -> Self {
self * rhs.multipli... |
let limbs = if cmp(self.limbs, rhs.limbs) == Less {
// Underflow occurs, so we compute the difference as `self + (-rhs)`.
add_no_overflow(self.limbs, (-rhs).limbs)
} else {
// No underflow, so it's faster to subtract directly.
sub(self.limbs, rhs.limbs)
... | identifier_body |
poisson_kriging.py | functions
def set_params(self, model,
joined_datasets, population_series, centroids_dataset,
id_col, val_col, pop_col,
lags_number, lag_step_size,
min_no_of_observations, search_radius):
self.model = model
self.joined_dat... |
def _predict_value(self, predicted_array, k_array, vals_of_neigh_areas):
w = np.linalg.solve(predicted_array, k_array)
zhat = (np.matrix(vals_of_neigh_areas * w[:-1])[0, 0])
if np.any(w < 0):
# Normalize weights
normalized_w = self.normalize_weights(w, zhat, 'ord... | """Function creates list of lists from dict of dicts in the order
given by the list with key names"""
new_list = []
for val in l:
subdict = d[val]
inner_list = []
for subval in l:
inner_list.append(subdict[subval])
new_list.append... | identifier_body |
poisson_kriging.py | preparation functions
def set_params(self, model,
joined_datasets, population_series, centroids_dataset,
id_col, val_col, pop_col,
lags_number, lag_step_size,
min_no_of_observations, search_radius):
self.model = model
sel... | (self, unknown_area):
"""Function prepares dict with distances for weighted distance calculation
between areas"""
new_d = self.joined_datasets.copy()
new_d = new_d.append(unknown_area, ignore_index=True)
try:
new_d['px'] = new_d['geometry'].apply(lambda v: v[0].x)
... | _prepare_distances_dict | identifier_name |
poisson_kriging.py | preparation functions
def set_params(self, model,
joined_datasets, population_series, centroids_dataset,
id_col, val_col, pop_col,
lags_number, lag_step_size,
min_no_of_observations, search_radius):
self.model = model
sel... | s = []
for wd in weighted_distances:
for k in known_centroids:
if wd[1] in k:
s.append(wd[0])
break
else:
pass
s = np.array(s).T
kriging_data =... |
if weighted:
weighted_distances = self._calculate_weighted_distances(unknown_areal_data_row,
areal_id) | random_line_split |
poisson_kriging.py | self.min_no_of_observations = min_no_of_observations
self.max_search_radius = search_radius
print('Parameters have been set')
def prepare_prediction_data(self, unknown_areal_data_row, unknown_areal_data_centroid,
weighted=False, verbose=False):
"""
... | sigmasq = (w.T * k_array)[0, 0]
if sigmasq < 0:
sigma = 0
else:
sigma = np.sqrt(sigmasq)
return zhat, sigma, w[-1][0], w, self.unknown_area_id | conditional_block | |
stream.go | : discoveryRequest,
xdsServer: s,
done: make(chan struct{}),
}
}
for {
select {
case <-ctx.Done():
metricsstore.DefaultMetricsStore.ProxyConnectCount.Dec()
return nil
case <-quit:
log.Debug().Msgf("gRPC stream with Envoy on Pod with UID=%s closed!", proxy.GetPodUID())
metricsstore.D... | {
resourcesRequested.Add(discoveryRequest.ResourceNames[idx])
} | conditional_block | |
stream.go | gRPC stream with Envoy on Pod with UID=%s closed!", proxy.GetPodUID())
metricsstore.DefaultMetricsStore.ProxyConnectCount.Dec()
return nil
case discoveryRequest, ok := <-requests:
if !ok {
log.Error().Msgf("Envoy with xDS Certificate SerialNumber=%s on Pod with UID=%s closed gRPC!", proxy.GetCertificate... | isCNforProxy | identifier_name | |
stream.go | }
typeURL := envoy.TypeURI(discoveryRequest.TypeUrl)
var typesRequest []envoy.TypeURI
if typeURL == envoy.TypeWildcard {
typesRequest = envoy.XDSResponseOrder
} else {
typesRequest = []envoy.TypeURI{typeURL}
}
<-s.workqueues.AddJob(newJob(typesRequest, &discoveryRequest))
case <-broadc... | } | random_line_split | |
stream.go | xdsServer: s,
done: make(chan struct{}),
}
}
for {
select {
case <-ctx.Done():
metricsstore.DefaultMetricsStore.ProxyConnectCount.Dec()
return nil
case <-quit:
log.Debug().Msgf("gRPC stream with Envoy on Pod with UID=%s closed!", proxy.GetPodUID())
metricsstore.DefaultMetricsStore.Pro... | {
resourcesRequested := mapset.NewSet()
for idx := range discoveryRequest.ResourceNames {
resourcesRequested.Add(discoveryRequest.ResourceNames[idx])
}
return resourcesRequested
} | identifier_body | |
main.py | 2
ORDER BY created DESC""", public_keys, ancestor)
else:
results = Result.gql(""" WHERE keys IN :1
ORDER BY created DESC""", public_keys)
metrics = set()
answers = []
for r in results:
metr... | .format(results['metric'], metric))
template = '404.html'
answers = results['answers']
# If the template hasn't been set by an error check above, give the
# metric-specific results page.
template = template or met... | if len(results['answers']) > 0:
if metric != results['metric']:
logging.error("Key is from metric {}, but {} requested." | random_line_split |
main.py | 2
ORDER BY created DESC""", public_keys, ancestor)
else:
results = Result.gql(""" WHERE keys IN :1
ORDER BY created DESC""", public_keys)
metrics = set()
answers = []
for r in results:
metr... | (self, *a, **kw):
self.response.write(*a, **kw)
def render_str(self, template, **params):
return jinja_environment.get_template(template).render(**params)
def render(self, template, **kw):
self.write(self.render_str(template, **kw))
def write_json(self, obj):
self.response... | write | identifier_name |
main.py | 2
ORDER BY created DESC""", public_keys, ancestor)
else:
results = Result.gql(""" WHERE keys IN :1
ORDER BY created DESC""", public_keys)
metrics = set()
answers = []
for r in results:
metr... |
class CompleteHandler(Handler):
def get(self, name):
key = self.request.get('private_key', None)
group = self.request.get('group', None)
answers = []
if key is None:
# If there's no key, then this is a preview. Don't try to load any
# answers.
... | logging.error('Could not find requested metric')
self.render('404.html') | conditional_block |
main.py | ))
def write_json(self, obj):
self.response.headers['Content-Type'] = "text/json; charset=utf-8"
self.write(json.dumps(obj))
class MainHandler(Handler):
def get(self):
self.render('index.html')
class TakeHandler(Handler):
def get(self, name):
metric = Metric.get_by_name(... | def get(self):
private_keys = json.loads(self.request.get('private_keys'))
group = self.request.get('group')
if private_keys:
for k in private_keys:
k.encode('ascii')
try:
response = Result.get_results(private_keys, group)
exce... | identifier_body | |
server.go | Response(id, result)
if err != nil {
w.Write([]byte(err.Error()))
} else {
w.Header().Set("Content-Type", "application/json")
w.Write(resBytes)
}
}
func writeDirectlyToResponse(w http.ResponseWriter, data []byte) {
w.Write(data)
}
func isNeedCacheMethod(config *Config, rpcReqMethod string) bool {
if config... |
var workerLoadBalanceIndex uint32 = 0
// teturns the order of workers according to the mode in the configuration
func getWorkersSequenceBySelectMode(config *Config, workerUris []string) []string {
if config.IsMostOfAllSelectMode() || config.IsFirstOfAllSelectMode() {
return workerUris
} else if config.IsOnlyFirs... | {
if config.IsOnlyFirstSelectMode() {
asyncTryWorkersUntilSuccess(config, workerUris, 0, responsesChannel, rpcReqMethod, reqBody)
} else {
for workerIndex, workerUri := range workerUris {
go func(workerIndex int, workerUri string) {
res := useWorkerToProvideService(config, workerIndex, workerUri, rpcReqMet... | identifier_body |
server.go | Response(id, result)
if err != nil {
w.Write([]byte(err.Error()))
} else {
w.Header().Set("Content-Type", "application/json")
w.Write(resBytes)
}
}
func writeDirectlyToResponse(w http.ResponseWriter, data []byte) {
w.Write(data)
}
func isNeedCacheMethod(config *Config, rpcReqMethod string) bool {
if config... | (config *Config, workerIndex int, workerUri string, rpcReqMethod string, reqBody []byte) *WorkerResponse {
res := new(WorkerResponse)
res.WorkerIndex = workerIndex
res.WorkerUri = workerUri
cache1Key := workerUri
cache2Key := string(reqBody)
// because of there will not be any '^' in workerUri, so join cache1Key... | useWorkerToProvideService | identifier_name |
server.go | "bytes"
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/zoowii/query_api_proxy/cache"
"sync/atomic"
"github.com/bitly/go-simplejson"
"github.com/zoowii/betterjson"
"gopkg.in/yaml.v2"
)
func ReadConfigFromYaml(yamlConfigFilePath string) (*Config, error) {
conf := NewConfig()
yamlFile, err := ioutil.ReadF... | random_line_split | ||
server.go | else {
w.Header().Set("Content-Type", "application/json")
w.Write(resBytes)
}
}
func writeResultToJSONRpcResponse(w http.ResponseWriter, id interface{}, result interface{}) {
resBytes, err := MakeJSONRpcSuccessResponse(id, result)
if err != nil {
w.Write([]byte(err.Error()))
} else {
w.Header().Set("Conte... | {
w.Write([]byte(err.Error()))
} | conditional_block | |
lib.rs | new Adler-32 instance with default state.
#[inline]
pub fn new() -> Self {
Self::default()
}
/// Creates an `Adler32` instance from a precomputed Adler-32 checksum.
///
/// This allows resuming checksum calculation without having to keep the `Adler32` instance
/// around.
///
... |
/// Returns the calculated checksum at this point in time.
#[inline]
pub fn checksum(&self) -> u32 {
(u32::from(self.b) << 16) | u32::from(self.a)
}
/// Adds `bytes` to the checksum calculation.
///
/// If efficiency matters, this should be called with Byte slices that contain at ... | {
Adler32 {
a: sum as u16,
b: (sum >> 16) as u16,
}
} | identifier_body |
lib.rs | {
a: u16,
b: u16,
}
impl Adler32 {
/// Creates a new Adler-32 instance with default state.
#[inline]
pub fn new() -> Self {
Self::default()
}
/// Creates an `Adler32` instance from a precomputed Adler-32 checksum.
///
/// This allows resuming checksum calculation without h... | Adler32 | identifier_name | |
lib.rs | //! - `#![no_std]` support (with `default-features = false`).
#![doc(html_root_url = "https://docs.rs/adler/0.2.2")]
// Deny a few warnings in doctests, since rustdoc `allow`s many warnings by default
#![doc(test(attr(deny(unused_imports, unused_must_use))))]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![warn(missing_debu... | //! This implementation features:
//!
//! - Permissively licensed (0BSD) clean-room implementation.
//! - Zero dependencies.
//! - Decent performance (3-4 GB/s). | random_line_split | |
lib.rs | ///
/// let mut sum = Adler32::from_checksum(partial);
/// sum.write_slice(parts[1].as_bytes());
/// assert_eq!(sum.checksum(), whole);
/// ```
#[inline]
pub fn from_checksum(sum: u32) -> Self {
Adler32 {
a: sum as u16,
b: (sum >> 16) as u16,
}
}
... | return Ok(h.checksum());
}
| conditional_block | |
main.rs | },
material::Scatter::Emit(emission) => {
// println!("Hit light!");
return emission * current_attenuation;
},
material::Scatter::Absorb => {
... | {
let mut current_ray = *ray;
let mut current_attenuation = Vec3::new(1.0, 1.0, 1.0);
for _depth in 0..50 {
if current_attenuation.length() < 1e-8 {
return Vec3::new(0.0, 0.0, 0.0)
}
match world.hit(¤t_ray, 0.00001, 1e20) {
None => {
... | identifier_body | |
main.rs | mut current_attenuation = Vec3::new(1.0, 1.0, 1.0);
for _depth in 0..50 {
if current_attenuation.length() < 1e-8 {
return Vec3::new(0.0, 0.0, 0.0)
}
match world.hit(¤t_ray, 0.00001, 1e20) {
None => {
let unit_direction = vector... | (args: &Args)
{
let default_output_name = "out".to_string();
let output_name = &args.o.as_ref().unwrap_or(&default_output_name);
let default_input_name = "/dev/stdin".to_string();
let input_name = &args.i.as_ref().unwrap_or(&default_input_name);
let br = BufReader::new(File::open... | write_image | identifier_name |
main.rs | mut current_attenuation = Vec3::new(1.0, 1.0, 1.0);
for _depth in 0..50 {
if current_attenuation.length() < 1e-8 {
return Vec3::new(0.0, 0.0, 0.0)
}
match world.hit(¤t_ray, 0.00001, 1e20) {
None => {
let unit_direction = vector... |
//////////////////////////////////////////////////////////////////////////////
// my own bastardized version of a float file format, horrendously inefficient
fn write_image_to_file(image: &Vec<Vec<Vec3>>, samples_so_far: usize, subsample: usize, file_prefix: &String)
{
println!("Writing output to {}",
... | random_line_split | |
main.rs | mut current_attenuation = Vec3::new(1.0, 1.0, 1.0);
for _depth in 0..50 {
if current_attenuation.length() < 1e-8 {
return Vec3::new(0.0, 0.0, 0.0)
}
match world.hit(¤t_ray, 0.00001, 1e20) {
None => {
let unit_direction = vector... | ;
let albedo = hr.material.albedo(¤t_ray, &next_values.1, &hr.normal);
current_ray = next_values.1;
current_attenuation = current_attenuation * albedo * next_values.0;
}
}
}
current_attenuation
}
/////////////////////////////////////////... | {
return Vec3::new(0.0, 0.0, 0.0);
} | conditional_block |
mod.rs | /// A user-defined function is really a closure, it has a scope
/// where it is defined and a body of items.
UserDefined(ScopeRef, Vec<sass::Item>),
}
impl PartialOrd for FuncImpl {
fn partial_cmp(&self, rhs: &Self) -> Option<cmp::Ordering> {
match (self, rhs) {
(&FuncImpl::Builtin(..)... | (
args: FormalArgs,
pos: SourcePos,
scope: ScopeRef,
body: Vec<sass::Item>,
) -> Self {
Function {
args,
pos,
body: FuncImpl::UserDefined(scope, body),
}
}
/// Call the function from a given scope and with a given set of
... | closure | identifier_name |
mod.rs | /// A user-defined function is really a closure, it has a scope
/// where it is defined and a body of items.
UserDefined(ScopeRef, Vec<sass::Item>),
}
impl PartialOrd for FuncImpl {
fn partial_cmp(&self, rhs: &Self) -> Option<cmp::Ordering> {
match (self, rhs) {
(&FuncImpl::Builtin(..)... | fn get_va_list(s: &Scope, name: Name) -> Result<Vec<Value>, Error> {
get_checked(s, name, check::va_list)
}
fn expected_to<'a, T>(value: &'a T, cond: &str) -> String
where
Formatted<'a, T>: std::fmt::Display,
{
format!(
"Expected {} to {}.",
Formatted {
value,
format... | get_checked(s, name.into(), check::string)
}
| random_line_split |
mod.rs | /// A user-defined function is really a closure, it has a scope
/// where it is defined and a body of items.
UserDefined(ScopeRef, Vec<sass::Item>),
}
impl PartialOrd for FuncImpl {
fn partial_cmp(&self, rhs: &Self) -> Option<cmp::Ordering> {
match (self, rhs) {
(&FuncImpl::Builtin(..)... |
/// Call the function from a given scope and with a given set of
/// arguments.
pub fn call(
&self,
callscope: ScopeRef,
args: CallArgs,
) -> Result<Value, Error> {
let cs = "%%CALLING_SCOPE%%";
match self.body {
FuncImpl::Builtin(ref body) => {
... | {
Function {
args,
pos,
body: FuncImpl::UserDefined(scope, body),
}
} | identifier_body |
tic_tac_toe.py | 8]]) == {player}
d2_win = set(self.data[[2, 4, 6]]) == {player}
if any([row_win, col_win, d1_win, d2_win]):
return ("win", player)
if self.counter["_"] == 0:
return ("tie", None)
else:
return ("turn", "1" if self.counter["1"] == self.coun... | )
else:
return "\n".join([indent_char + " ".join(row) for row in board_symbols])
def gen_game_tree(state_init):
"""Generate full game tree from initial state"""
current_path = [state_init]
game_tree = {}
while current_path:
cur_state = current_path[-1]
... | """Returns a string representing the game board for printing"""
symbols = symbols or self.symbols
assert len(symbols) == 2, "`symbols` must have exactly 2 elements"
data_symbols = self.data.copy()
for orig, new in zip(("1", "2"), symbols):
data_symbols[data_symbols == orig] ... | identifier_body |
tic_tac_toe.py | 8]]) == {player}
d2_win = set(self.data[[2, 4, 6]]) == {player}
if any([row_win, col_win, d1_win, d2_win]):
return ("win", player)
if self.counter["_"] == 0:
return ("tie", None)
else:
return ("turn", "1" if self.counter["1"] == self.coun... | (self):
"""Determine possible next moves. Returns a dict {index: new_state}"""
status, player = self.game_status
moves = {}
if status == "turn":
for idx in np.where(self.data == "_")[0]:
new_move = self.data.copy()
new_move[idx] = player
... | find_next_states | identifier_name |
tic_tac_toe.py | 8]]) == {player}
d2_win = set(self.data[[2, 4, 6]]) == {player}
if any([row_win, col_win, d1_win, d2_win]):
return ("win", player)
if self.counter["_"] == 0:
return ("tie", None)
else:
return ("turn", "1" if self.counter["1"] == self.coun... | board_symbols = data_symbols.reshape((3, 3))
if legend_hint:
legend_board = np.where(
self.data == "_", range(9), " ").reshape((3, 3))
return "\n".join(
[indent_char + "GAME | INDEX"]
+ [indent_char + "===== | ====="]
... | data_symbols[data_symbols == orig] = new
| random_line_split |
tic_tac_toe.py | _char + " ".join(row) for row in board_symbols])
def gen_game_tree(state_init):
"""Generate full game tree from initial state"""
current_path = [state_init]
game_tree = {}
while current_path:
cur_state = current_path[-1]
if cur_state not in game_tree:
ttt = TicTacToe(cur_st... | print(f"{val} is not a valid value. Please choose from: {choices}") | conditional_block | |
web-trader - console.py | :
Current stock price for a symbol from Yahoo! Finance or
-1 if price could not be extracted.
'''
price = -1
url = 'https://finance.yahoo.com/quote/'+symbol
page = req.urlopen(url).read()
soup = BeautifulSoup(page, 'html.parser')
scripts = soup.findAll('script')
# Cycle... | ():
'''Displays current P/L with updated market price.'''
print('\nCURRENT P/L')
print('{:<7s} {:>10s} {:>10s} {:>10s} {:>10s} {:>10s}'.format(
'Ticker','Position','Market','WAP','UPL','RPL')
)
for index, row in pl.iterrows():
price = getPrice(row['Ticker'])
print('{:<7s}... | showPL | identifier_name |
web-trader - console.py | Returns:
Current stock price for a symbol from Yahoo! Finance or
-1 if price could not be extracted.
'''
price = -1
url = 'https://finance.yahoo.com/quote/'+symbol
page = req.urlopen(url).read()
soup = BeautifulSoup(page, 'html.parser')
scripts = soup.findAll('script')
... |
def doBuy(symbol, volume):
'''
Buys given amount of selected stock.
Args:
symbol: Stock to purchase.
volume: Number of shares to purchase.
Returns:
TRUE if successful and FALSE otherwise.
'''
global cash
global blotter
global pl
global db
# ... | '''Prompt for and return stock symbol to buy or sell.
Argument is either "buy" or "sell".'''
symbol = input('Enter stock symbol to {:s}: '.format(side)).upper()
if symbol not in symbols:
print ('Invalid symbol. Valid symbols:')
for s in symbols:
print(s, end=" ")
pr... | identifier_body |
web-trader - console.py | # Global variables
symbols = ('AAPL','AMZN','MSFT','INTC','SNAP')
menu = ['[B]uy','[S]ell','Show [P]/L','Show Blotte[r]','[Q]uit']
initial_cash = 10000000.00
cash = 0.00
blotter = pd.DataFrame(columns=['Side','Ticker','Volume','Price','Date','Cash'])
pl = pd.DataFrame(columns=['Ticker','Position','WAP','RPL'])
# Sto... | from datetime import datetime
from pymongo import MongoClient
| random_line_split | |
web-trader - console.py | Returns:
Current stock price for a symbol from Yahoo! Finance or
-1 if price could not be extracted.
'''
price = -1
url = 'https://finance.yahoo.com/quote/'+symbol
page = req.urlopen(url).read()
soup = BeautifulSoup(page, 'html.parser')
scripts = soup.findAll('script')
... |
print('Invalid choice. Please try again.\n')
def connectDB():
'''Connects to database.'''
global db
client = MongoClient("mongodb://trader:traderpw@data602-shard-00-00-thsko.mongodb.net:27017,data602-shard-00-01-thsko.mongodb.net:27017,data602-shard-00-02-thsko.mongodb.net:27017/test?ssl=tru... | return option | conditional_block |
provider_test.go | Mxnhfag5qlrObQW3K2miTpGYkl
CIRRNFMIvwJBAPtatE1evu25R3NSTU2YwQgkEymh40PW+lncYge6ZqZGfK7J5JBK
wr1ug7KjTJgIfY2Sg2VHn56HAdA4RUl2xOcCQQDZqnTxpQ6DHYSFqwg04cHhYP8H
QOF0Z8WnEX4g8Em/N2X26BK+wKXig2d6fIhghu/fLaNKZJK8FOK8CE1GDuWPAkEA
wrP6Ysx3vZH+JPil5Ovk6zd2mJNMhmpqt10dmrrrdPW483R01sjynOaUobYZSNOa
3iWWHsgifxw5bV+JXGTiFQJBAKwh6Hvli... | "name1", | random_line_split | |
provider_test.go | RM9KAlUipIFkCAwEAAaNFMEMwDgYDVR0PAQH/BAQD
AgEGMBIGA1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0OBBYEFP8lIbNl3zZPEHF17cFU
NFsK/0/oMA0GCSqGSIb3DQEBCwUAA4GBADMCd4nzc19voa60lNknhsihcfyNUeUt
EEsLCceK+9F1u2Xdj+mTNOh3MI+5m7wmFLiHuUtQovHMJ4xUpoHa6Iznc+QCbow4
SMO3sf1847tASv3eUFwEUt9vv39vtey6C6ftiUUImzZYfx6FO/A62uGEg2w3IOJ+
3cCXYiulfsyv
-----... |
cert = ssh.Certificate{
Nonce: []byte("ssoca-fake1"),
Key: publicKey,
CertType: ssh.UserCert,
}
})
It("signs certificate", func() {
subject = NewProvider(
"name1",
Config{
CertificatePath: "/path/ca1/certificate",
PrivateKeyPath: "/path/ca1/private_key",
| {
Fail("parsing to public key")
} | conditional_block |
MessageSigner.go | dsa.PublicKey) error {
var err error
message := payload
// first sign, then encrypt as per RFC
if signer.signMessages {
message, _ = CreateJWSSignature(string(payload), signer.privateKey)
}
emessage, err := EncryptMessage(message, publicKey)
err = signer.messenger.Publish(address, retained, emessage)
return e... | {
reflSender = reflObject.FieldByName("Address")
if !reflSender.IsValid() {
err = errors.New("VerifySenderJWSSignature: object doesn't have a Sender or Address field")
return true, err
}
} | conditional_block | |
MessageSigner.go | ignature(dmessage, object, signer.GetPublicKey)
return isEncrypted, isSigned, err
}
// SignMessages returns whether messages MUST be signed on sending or receiving
func (signer *MessageSigner) SignMessages() bool {
return signer.signMessages
}
// VerifySignedMessage parses and verifies the message signature
// as p... | func (signer *MessageSigner) PublishEncrypted(
address string, retained bool, payload string, publicKey *ecdsa.PublicKey) error {
var err error
message := payload
// first sign, then encrypt as per RFC
if signer.signMessages {
message, _ = CreateJWSSignature(string(payload), signer.privateKey)
}
emessage, err ... | }
// PublishEncrypted sign and encrypts the payload and publish the resulting message on the given address
// Signing only happens if the publisher's signingMethod is set to SigningMethodJWS | random_line_split |
MessageSigner.go | ature(dmessage, object, signer.GetPublicKey)
return isEncrypted, isSigned, err
}
// SignMessages returns whether messages MUST be signed on sending or receiving
func (signer *MessageSigner) SignMessages() bool {
return signer.signMessages
}
// VerifySignedMessage parses and verifies the message signature
// as per ... | (message string, publicKey *ecdsa.PublicKey) (serialized string, err error) {
var jwe *jose.JSONWebEncryption
recpnt := jose.Recipient{Algorithm: jose.ECDH_ES, Key: publicKey}
encrypter, err := jose.NewEncrypter(jose.A128CBC_HS256, recpnt, nil)
if encrypter != nil {
jwe, err = encrypter.Encrypt([]byte(message)... | EncryptMessage | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.