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 |
|---|---|---|---|---|
images.py | from tgen.images import Images, ttypes as o
from lib.blobby import Blobby, o as bo
from lib.discovery import connect
from redis import Redis
import time
from lib.imgcompare.avg import average_hash
from cStringIO import StringIO
from PIL import Image
# events we will fire:
# image_added : source_page_url, source_url,... | (object):
def __init__(self, redis_host='127.0.0.1'):
self.redis_host = redis_host
self.rc = Redis(redis_host)
self.revent = ReventClient(redis_host=self.redis_host)
# redis keys
# incr this for the next image id
# images:next_id = next_id
# all the images ... | ImagesHandler | identifier_name |
bert_tagger_trainer.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# file: bert_tagger_trainer.py
import os
import re
import argparse
import logging
from typing import Dict
from collections import namedtuple
from utils.random_seed import set_random_seed
set_random_seed(0)
import torch
import pytorch_lightning as pl
from torch import Te... | all_counts = torch.stack([x[f'span_f1_stats'] for x in outputs]).view(-1, 3).sum(0)
span_tp, span_fp, span_fn = all_counts
span_recall = span_tp / (span_tp + span_fn + 1e-10)
span_precision = span_tp / (span_tp + span_fp + 1e-10)
span_f1 = span_precision * span_recall * 2 / (span... |
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 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# file: bert_tagger_trainer.py
import os
import re
import argparse
import logging
from typing import Dict
from collections import namedtuple
from utils.random_seed import set_random_seed
set_random_seed(0)
import torch
import pytorch_lightning as pl
from torch import Te... |
if prefix == "train":
batch_size = self.args.train_batch_size
# define data_generator will help experiment reproducibility.
# cannot use random data sampler since the gradient may explode.
data_generator = torch.Generator()
data_generator.manual_seed... | dataset = TruncateDataset(dataset, limit) | conditional_block |
bert_tagger_trainer.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# file: bert_tagger_trainer.py
import os
import re
import argparse
import logging
from typing import Dict
from collections import namedtuple
from utils.random_seed import set_random_seed
set_random_seed(0)
import torch
import pytorch_lightning as pl
from torch import Te... | (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 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# file: bert_tagger_trainer.py
import os
import re
import argparse
import logging
from typing import Dict
from collections import namedtuple
from utils.random_seed import set_random_seed
set_random_seed(0)
import torch
import pytorch_lightning as pl
from torch import Te... |
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 | import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/switchMap';
import { Location } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import ... | 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 | import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/switchMap';
import { Location } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import ... | 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 | import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/switchMap';
import { Location } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import ... | 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 | import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/switchMap';
import { Location } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import ... | 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 | var fs = require('fs');
var archiver = require('archiver');
var express = require('express');
var multer = require('multer');
var path = require('path');
var cheerio = require('cheerio');
var es = require('event-stream');
var parse = require('csv-parse');
var Datauri = require('datauri');
var lunr = require('lunr');
va... |
return undefined;
}
function includeSearch (archive, options) {
var search_index = JSON.stringify(options.idx.toJSON());
var search_module = "define([], function () { return " + search_index + "; });";
archive.append(search_module, { name: "/search_index.js" });
}
function includeTranscriptFolders (archive, op... | {
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 | var fs = require('fs');
var archiver = require('archiver');
var express = require('express');
var multer = require('multer');
var path = require('path');
var cheerio = require('cheerio');
var es = require('event-stream');
var parse = require('csv-parse');
var Datauri = require('datauri');
var lunr = require('lunr');
va... |
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 | var fs = require('fs');
var archiver = require('archiver');
var express = require('express');
var multer = require('multer');
var path = require('path');
var cheerio = require('cheerio');
var es = require('event-stream');
var parse = require('csv-parse');
var Datauri = require('datauri');
var lunr = require('lunr');
va... | (archive, options) {
var search_index = JSON.stringify(options.idx.toJSON());
var search_module = "define([], function () { return " + search_index + "; });";
archive.append(search_module, { name: "/search_index.js" });
}
function includeTranscriptFolders (archive, options) {
var returnDir = options.name + optio... | includeSearch | identifier_name |
app.js | var fs = require('fs');
var archiver = require('archiver');
var express = require('express');
var multer = require('multer');
var path = require('path');
var cheerio = require('cheerio');
var es = require('event-stream');
var parse = require('csv-parse');
var Datauri = require('datauri');
var lunr = require('lunr');
va... | options.toc[tocReference.index].transcript = "media/transcript/" + transcriptFilename;
options.idx.add(doc);
}
});
} else if (entry.fileName.indexOf(".dfxp") != -1) {
var writePath = path.join(targetDir + "/media/transcript/", entry.fileName);
// ensure parent directory exists
... | var transcriptFilename = path.basename(newFilename, path.extname(newFilename)) + ".dfxp"; | random_line_split |
retransmit_stage.rs | //! The `retransmit_stage` retransmits shreds between validators
#![allow(clippy::rc_buffer)]
use {
crate::{
ancestor_hashes_service::AncestorHashesReplayUpdateReceiver,
cluster_info_vote_listener::VerifiedVoteReceiver,
cluster_nodes::ClusterNodesCache,
cluster_slots::ClusterSlots,
... |
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 | //! The `retransmit_stage` retransmits shreds between validators
#![allow(clippy::rc_buffer)]
use {
crate::{
ancestor_hashes_service::AncestorHashesReplayUpdateReceiver,
cluster_info_vote_listener::VerifiedVoteReceiver,
cluster_nodes::ClusterNodesCache,
cluster_slots::ClusterSlots,
... | (
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 | //! The `retransmit_stage` retransmits shreds between validators
#![allow(clippy::rc_buffer)]
use {
crate::{
ancestor_hashes_service::AncestorHashesReplayUpdateReceiver,
cluster_info_vote_listener::VerifiedVoteReceiver,
cluster_nodes::ClusterNodesCache,
cluster_slots::ClusterSlots,
... | 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 | export default {
error: {
generic: 'Error',
home: 'Go home'
},
kara: {
phrase: '{songtype} from {series}',
meta: '{songtitle} from {serieSinger}',
notfound: 'Karaoke not found',
tagtypes: {
series: 'Series',
langs: 'Language | Languages',
songtypes: 'Song type | Song types',
singers: 'Singer ... | placeholder: 'LoveLiveFan93'
},
password: {
header: 'Change password',
label: 'Password',
placeholder: 'EnVraiJePréfèreIdolM@ster'
},
password_confirmation: {
label: 'Password confirmation',
placeholder: 'EnVraiJePréfèreIdolM@ster'
},
email: {
label: 'Email',
... | nickname: {
label: 'Nickname', | random_line_split |
quadstore.go | package sql
import (
"database/sql"
"database/sql/driver"
"encoding/hex"
"fmt"
"strings"
"time"
"github.com/cayleygraph/cayley/clog"
"github.com/cayleygraph/cayley/graph"
"github.com/cayleygraph/cayley/graph/iterator"
"github.com/cayleygraph/cayley/internal/lru"
"github.com/cayleygraph/cayley/quad"
"githu... | clog.Infof("NameOf was nil")
}
return nil
} else if v, ok := v.(graph.PreFetchedValue); ok {
return v.NameOf()
}
hash := v.(NodeHash)
if !hash.Valid() {
if clog.V(2) {
clog.Infof("NameOf was nil")
}
return nil
}
if val, ok := qs.ids.Get(hash.String()); ok {
return val.(quad.Value)
}
query :=... | func (qs *QuadStore) NameOf(v graph.Value) quad.Value {
if v == nil {
if clog.V(2) { | random_line_split |
quadstore.go | package sql
import (
"database/sql"
"database/sql/driver"
"encoding/hex"
"fmt"
"strings"
"time"
"github.com/cayleygraph/cayley/clog"
"github.com/cayleygraph/cayley/graph"
"github.com/cayleygraph/cayley/graph/iterator"
"github.com/cayleygraph/cayley/internal/lru"
"github.com/cayleygraph/cayley/quad"
"githu... | (isAll bool, dir quad.Direction, hash NodeHash) int64 {
var err error
if isAll {
return qs.Size()
}
if qs.noSizes {
if dir == quad.Predicate {
return (qs.Size() / 100) + 1
}
return (qs.Size() / 1000) + 1
}
if val, ok := qs.sizes.Get(hash.String() + string(dir.Prefix())); ok {
return val.(int64)
}
v... | sizeForIterator | identifier_name |
quadstore.go | package sql
import (
"database/sql"
"database/sql/driver"
"encoding/hex"
"fmt"
"strings"
"time"
"github.com/cayleygraph/cayley/clog"
"github.com/cayleygraph/cayley/graph"
"github.com/cayleygraph/cayley/graph/iterator"
"github.com/cayleygraph/cayley/internal/lru"
"github.com/cayleygraph/cayley/quad"
"githu... |
return graph.NewSequentialKey(horizon)
}
func (qs *QuadStore) FixedIterator() graph.FixedIterator {
return iterator.NewFixed(iterator.Identity)
}
func (qs *QuadStore) Close() error {
return qs.db.Close()
}
func (qs *QuadStore) QuadDirection(in graph.Value, d quad.Direction) graph.Value {
return NodeHash(in.(Qua... | {
if err != sql.ErrNoRows {
clog.Errorf("Couldn't execute horizon: %v", err)
}
return graph.NewSequentialKey(0)
} | conditional_block |
quadstore.go | package sql
import (
"database/sql"
"database/sql/driver"
"encoding/hex"
"fmt"
"strings"
"time"
"github.com/cayleygraph/cayley/clog"
"github.com/cayleygraph/cayley/graph"
"github.com/cayleygraph/cayley/graph/iterator"
"github.com/cayleygraph/cayley/internal/lru"
"github.com/cayleygraph/cayley/quad"
"githu... |
func (qs *QuadStore) Close() error {
return qs.db.Close()
}
func (qs *QuadStore) QuadDirection(in graph.Value, d quad.Direction) graph.Value {
return NodeHash(in.(QuadHashes).Get(d))
}
func (qs *QuadStore) Type() string {
return QuadStoreType
}
func (qs *QuadStore) sizeForIterator(isAll bool, dir quad.Direction... | {
return iterator.NewFixed(iterator.Identity)
} | identifier_body |
tbs.rs | //! hash functions for DNSSec operations
use super::rdata::{sig, DNSSECRData, SIG};
use crate::error::*;
use crate::rr::dnssec::Algorithm;
use crate::rr::{DNSClass, Name, RData, Record, RecordType};
use crate::serialize::binary::{BinEncodable, BinEncoder, EncodeMode};
/// Data To Be Signed.
pub struct TBS(Vec<u8>);
... | (
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 | //! hash functions for DNSSec operations
use super::rdata::{sig, DNSSECRData, SIG};
use crate::error::*;
use crate::rr::dnssec::Algorithm;
use crate::rr::{DNSClass, Name, RData, Record, RecordType};
use crate::serialize::binary::{BinEncodable, BinEncoder, EncodeMode};
/// Data To Be Signed.
pub struct TBS(Vec<u8>);
... |
/// Returns the to-be-signed serialization of the given record set using the information
/// provided from the RRSIG record.
///
/// # Arguments
///
/// * `rrsig` - SIG or RRSIG record, which was produced from the RRSet
/// * `records` - RRSet records to sign with the information in the `rrsig`
///
/// # Return
///
/... | {
// 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 | //! hash functions for DNSSec operations
use super::rdata::{sig, DNSSECRData, SIG};
use crate::error::*;
use crate::rr::dnssec::Algorithm;
use crate::rr::{DNSClass, Name, RData, Record, RecordType};
use crate::serialize::binary::{BinEncodable, BinEncoder, EncodeMode};
/// Data To Be Signed.
pub struct TBS(Vec<u8>);
... | {
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 | //! hash functions for DNSSec operations
use super::rdata::{sig, DNSSECRData, SIG};
use crate::error::*;
use crate::rr::dnssec::Algorithm;
use crate::rr::{DNSClass, Name, RData, Record, RecordType};
use crate::serialize::binary::{BinEncodable, BinEncoder, EncodeMode};
/// Data To Be Signed.
pub struct TBS(Vec<u8>);
... |
// if rrsig_labels < fqdn_labels,
// name = "*." | the rightmost rrsig_label labels of the
// fqdn
if num_labels < fqdn_labels {
let mut star_name: Name = Name::from_labels(vec![b"*" as &[u8]]).unwrap();
let rightmost = na... | {
return Ok(name.clone());
} | conditional_block |
index.js | var util = require('util');
var ardrone = require('ar-drone-browserified');
var parseAT = require('./lib/atreader');
var createCam = require('voxel-camera');
var tic = require('tic')();
var Drone = function(options) {
var self = this;
if (options.THREE) options = {game:options};
if (!options.... | (t, from, to, d) {
var should = to > 0
? from < to ? true : false
: from > to ? true : false;
if (!should) return from;
t /= d || 100;
return -to * t * (t - 2) + from;
};
var TAU = Math.PI * 2;
function deg2Rad(deg) { return deg * (Math.PI / 180); }
| anim | identifier_name |
index.js | var util = require('util');
var ardrone = require('ar-drone-browserified');
var parseAT = require('./lib/atreader');
var createCam = require('voxel-camera');
var tic = require('tic')();
var Drone = function(options) {
var self = this;
if (options.THREE) options = {game:options};
if (!options.... | });
// 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 | var util = require('util');
var ardrone = require('ar-drone-browserified');
var parseAT = require('./lib/atreader');
var createCam = require('voxel-camera');
var tic = require('tic')();
var Drone = function(options) {
var self = this;
if (options.THREE) options = {game:options};
if (!options.... |
// animate values to produce smoother results
function anim(t, from, to, d) {
var should = to > 0
? from < to ? true : false
: from > to ? true : false;
if (!should) return from;
t /= d || 100;
return -to * t * (t - 2) + from;
};
var TAU = Math.PI * 2;
function deg2Rad(deg) { return deg * (Math.PI / ... | {
if (arguments.length < 3) {
y = x; z = x;
}
item.x = x; item.y = y; item.z = z;
} | identifier_body |
function.py | # -*- coding:utf-8 -*-
import os
import sys
projectRoot = '/media/wangchen/newdata1/wangchen/work/Indoor_caffe/'
caffePath = '/home/wangchen/caffe'
os.environ['CAFFE_ROOT'] = caffePath
try:
caffe_root = os.environ['CAFFE_ROOT'] + '/'
print caffe_root
except KeyError:
raise KeyError("Define C... | 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 | # -*- coding:utf-8 -*-
import os
import sys
projectRoot = '/media/wangchen/newdata1/wangchen/work/Indoor_caffe/'
caffePath = '/home/wangchen/caffe'
os.environ['CAFFE_ROOT'] = caffePath
try:
caffe_root = os.environ['CAFFE_ROOT'] + '/'
print caffe_root
except KeyError:
raise KeyError("Define C... | 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 | # -*- coding:utf-8 -*-
import os
import sys
projectRoot = '/media/wangchen/newdata1/wangchen/work/Indoor_caffe/'
caffePath = '/home/wangchen/caffe'
os.environ['CAFFE_ROOT'] = caffePath
try:
caffe_root = os.environ['CAFFE_ROOT'] + '/'
print caffe_root
except KeyError:
raise KeyError("Define C... | 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 | # -*- coding:utf-8 -*-
import os
import sys
projectRoot = '/media/wangchen/newdata1/wangchen/work/Indoor_caffe/'
caffePath = '/home/wangchen/caffe'
os.environ['CAFFE_ROOT'] = caffePath
try:
caffe_root = os.environ['CAFFE_ROOT'] + '/'
print caffe_root
except KeyError:
raise KeyError("Define C... | 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 |
import ts from 'typescript';
type Dictionary<T> = { [key: string]: T };
type Nullable<T> = T | null;
class | {
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 | import ts from 'typescript';
type Dictionary<T> = { [key: string]: T };
type Nullable<T> = T | null;
class ParsedNode {
constructor(public tagName: string = "", public parentNode: Nullable<ParsedNode> = null) { }
localVariables: string[] = [];
childNodes: ParsedNode[] = [];
startText: string = "";
... | }
export = vue2jsx; | pos++;
return pos;
}
| random_line_split |
vue2jsx.ts |
import ts from 'typescript';
type Dictionary<T> = { [key: string]: T };
type Nullable<T> = T | null;
class ParsedNode {
constructor(public tagName: string = "", public parentNode: Nullable<ParsedNode> = null) { }
localVariables: string[] = [];
childNodes: ParsedNode[] = [];
startText: string = "";
... |
}
export = vue2jsx; | {
while(/\s/.test(jsCode.substr(pos, 1)) && pos < jsCode.length)
pos++;
return pos;
} | identifier_body |
cme_stats.py | """
Generate stats for correct (true pos), missed (false neg), extraneous (false pos) using the top-n datasets returned
Creates a json/csv files. Look in stats_and_csv folder to see what the output look like
"""
import json
import re
from collections import defaultdict
from enum import Enum
import os
# When I ran... | 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 | """
Generate stats for correct (true pos), missed (false neg), extraneous (false pos) using the top-n datasets returned
Creates a json/csv files. Look in stats_and_csv folder to see what the output look like
"""
import json
import re
from collections import defaultdict
from enum import Enum
import os
# When I ran... | (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 | """
Generate stats for correct (true pos), missed (false neg), extraneous (false pos) using the top-n datasets returned
Creates a json/csv files. Look in stats_and_csv folder to see what the output look like
"""
import json
import re
from collections import defaultdict
from enum import Enum
import os
# When I ran... |
if __name__ == '__main__':
# User Parameters
features_location = 'cmr_results/giovanni/giovanni_papers_features.json' # the extracted features
key_title_ground_truth_location = 'cmr_results/giovanni/giovanni_papers_key_title_ground_truth.json' # includes the ground truth if applicables
n = 1 # ran... | 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 | """
Generate stats for correct (true pos), missed (false neg), extraneous (false pos) using the top-n datasets returned
Creates a json/csv files. Look in stats_and_csv folder to see what the output look like
"""
import json
import re
from collections import defaultdict
from enum import Enum
import os
# When I ran... |
# 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 | // Copyright 2022 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use aes::cipher::generic_array::GenericArray;
use aes::{Aes128, BlockDecrypt, BlockEncrypt, NewBlockCipher};
use fuchsia_inspect::{self as inspect, Propert... |
#[test]
fn mark_used_nonexistent_key_is_error() {
let mut list = AccountKeyList::with_capacity_and_keys(1, vec![]);
let key = AccountKey::new([1; 16]);
assert_matches!(list.mark_used(&key), Err(_));
}
#[fuchsia::test]
fn load_keys_from_nonexistent_file() {
const EX... | {
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 | // Copyright 2022 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use aes::cipher::generic_array::GenericArray;
use aes::{Aes128, BlockDecrypt, BlockEncrypt, NewBlockCipher};
use fuchsia_inspect::{self as inspect, Propert... | /// 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 | // Copyright 2022 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use aes::cipher::generic_array::GenericArray;
use aes::{Aes128, BlockDecrypt, BlockEncrypt, NewBlockCipher};
use fuchsia_inspect::{self as inspect, Propert... |
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 | // Copyright 2022 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use aes::cipher::generic_array::GenericArray;
use aes::{Aes128, BlockDecrypt, BlockEncrypt, NewBlockCipher};
use fuchsia_inspect::{self as inspect, Propert... | () {
let invalid_id = 0x1ffabcd;
assert_matches!(ModelId::try_from(invalid_id), Err(_));
}
#[test]
fn empty_account_key_list_service_data() {
let empty = AccountKeyList::with_capacity_and_keys(1, vec![]);
let service_data = empty.service_data().expect("can build service data... | invalid_model_id_conversion_is_error | identifier_name |
utils.rs | use cairo;
use cairo::enums::{FontSlant, FontWeight};
use cairo::prelude::SurfaceExt;
use clap::{
crate_authors, crate_description, crate_name, crate_version, value_t, App, AppSettings, Arg,
};
use css_color_parser::Color as CssColor;
use font_loader::system_fonts;
use itertools::Itertools;
use log::debug;
use rege... | ;
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 | use cairo;
use cairo::enums::{FontSlant, FontWeight};
use cairo::prelude::SurfaceExt;
use clap::{
crate_authors, crate_description, crate_name, crate_version, value_t, App, AppSettings, Arg,
};
use css_color_parser::Color as CssColor;
use font_loader::system_fonts;
use itertools::Itertools;
use log::debug;
use rege... | () {
assert!(!intersects((1905, 705, 31, 82), (2000, 723, 38, 64)));
}
}
| test_no_intersect | identifier_name |
utils.rs | use cairo;
use cairo::enums::{FontSlant, FontWeight};
use cairo::prelude::SurfaceExt;
use clap::{
crate_authors, crate_description, crate_name, crate_version, value_t, App, AppSettings, Arg,
};
use css_color_parser::Color as CssColor;
use font_loader::system_fonts;
use itertools::Itertools;
use log::debug;
use rege... |
/// Sort list of `DesktopWindow`s by position.
///
/// This sorts by column first and row second.
pub fn sort_by_pos(mut dws: Vec<DesktopWindow>) -> Vec<DesktopWindow> {
dws.sort_by_key(|w| w.pos.0);
dws.sort_by_key(|w| w.pos.1);
dws
}
/// Returns true if `r1` and `r2` overlap.
fn intersects(r1: (i32, i3... | {
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 | use cairo;
use cairo::enums::{FontSlant, FontWeight};
use cairo::prelude::SurfaceExt;
use clap::{
crate_authors, crate_description, crate_name, crate_version, value_t, App, AppSettings, Arg,
};
use css_color_parser::Color as CssColor;
use font_loader::system_fonts;
use itertools::Itertools;
use log::debug;
use rege... | "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 | // Copyright 2020 Datafuse Labs.
//
// 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 ... | fn build_runtime() -> Result<tokio::runtime::Runtime> {
tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.map_err(|tokio_error| ErrorCode::TokioError(format!("{}", tokio_error)))
}
}
impl<W: std::io::Write> InteractiveWorker<W> {
pub fn create(s... | }
| random_line_split |
mysql_interactive_worker.rs | // Copyright 2020 Datafuse Labs.
//
// 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 ... | (&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 | // Copyright 2020 Datafuse Labs.
//
// 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 ... |
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 | use itertools::multiunzip;
use rust_htslib::{bam, bam::ext::BamRecordExtensions};
use std::collections::HashMap;
use std::fmt::{Debug, Display};
/// Merge two lists into a sorted list
/// Normal sort is supposed to be very fast on two sorted lists
/// <https://doc.rust-lang.org/std/vec/struct.Vec.html#current-implemen... | <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 | use itertools::multiunzip;
use rust_htslib::{bam, bam::ext::BamRecordExtensions};
use std::collections::HashMap;
use std::fmt::{Debug, Display};
/// Merge two lists into a sorted list
/// Normal sort is supposed to be very fast on two sorted lists
/// <https://doc.rust-lang.org/std/vec/struct.Vec.html#current-implemen... | 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 | use itertools::multiunzip;
use rust_htslib::{bam, bam::ext::BamRecordExtensions};
use std::collections::HashMap;
use std::fmt::{Debug, Display};
/// Merge two lists into a sorted list
/// Normal sort is supposed to be very fast on two sorted lists
/// <https://doc.rust-lang.org/std/vec/struct.Vec.html#current-implemen... | else {
let aligned_block_pairs: Vec<([i64; 2], [i64; 2])> = record.aligned_block_pairs().collect();
liftover_exact(&aligned_block_pairs, reference_positions, true)
}
}
| {
reference_positions.iter().map(|_x| None).collect()
} | conditional_block |
lib.rs | use itertools::multiunzip;
use rust_htslib::{bam, bam::ext::BamRecordExtensions};
use std::collections::HashMap;
use std::fmt::{Debug, Display};
/// Merge two lists into a sorted list
/// Normal sort is supposed to be very fast on two sorted lists
/// <https://doc.rust-lang.org/std/vec/struct.Vec.html#current-implemen... |
/// 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 | // This file is part of the uutils coreutils package.
//
// (c) Jian Zeng <anonymousknight96@gmail.com>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
// spell-checker:ignore (ToDO) COMFOLLOW Chowner Passwd RFILE RFILE's derefer dgid du... | (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 | // This file is part of the uutils coreutils package.
//
// (c) Jian Zeng <anonymousknight96@gmail.com>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
// spell-checker:ignore (ToDO) COMFOLLOW Chowner Passwd RFILE RFILE's derefer dgid du... | )
.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 | // This file is part of the uutils coreutils package.
//
// (c) Jian Zeng <anonymousknight96@gmail.com>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
// spell-checker:ignore (ToDO) COMFOLLOW Chowner Passwd RFILE RFILE's derefer dgid du... |
Err(e) => {
if self.verbosity != Verbosity::Silent {
show_error!("{}", e);
}
1
}
}
}
ret
}
fn obtain_meta<P: AsRef<Path>>(&self, path: P, follow: bool) -> Option<Meta... | {
if !n.is_empty() {
show_error!("{}", n);
}
0
} | conditional_block |
bls12_377_scalar.rs | //! This module implements field arithmetic for BLS12-377's scalar field.
use std::cmp::Ordering::Less;
use std::convert::TryInto;
use std::ops::{Add, Div, Mul, Neg, Sub};
use rand::Rng;
use unroll::unroll_for_loops;
use crate::{add_no_overflow, cmp, Field, sub, field_to_biguint, rand_range, rand_range_from_rng};
us... | }
}
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 | //! This module implements field arithmetic for BLS12-377's scalar field.
use std::cmp::Ordering::Less;
use std::convert::TryInto;
use std::ops::{Add, Div, Mul, Neg, Sub};
use rand::Rng;
use unroll::unroll_for_loops;
use crate::{add_no_overflow, cmp, Field, sub, field_to_biguint, rand_range, rand_range_from_rng};
us... | ) {
assert_eq!(Bls12377Scalar::from_canonical_u64(0b10101).num_bits(), 5);
assert_eq!(Bls12377Scalar::from_canonical_u64(u64::max_value()).num_bits(), 64);
assert_eq!(Bls12377Scalar::from_canonical([0, 1, 0, 0]).num_bits(), 64 + 1);
assert_eq!(Bls12377Scalar::from_canonical([0, 0, 0, 1])... | um_bits( | identifier_name |
bls12_377_scalar.rs | //! This module implements field arithmetic for BLS12-377's scalar field.
use std::cmp::Ordering::Less;
use std::convert::TryInto;
use std::ops::{Add, Div, Mul, Neg, Sub};
use rand::Rng;
use unroll::unroll_for_loops;
use crate::{add_no_overflow, cmp, Field, sub, field_to_biguint, rand_range, rand_range_from_rng};
us... | }
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 | //! This module implements field arithmetic for BLS12-377's scalar field.
use std::cmp::Ordering::Less;
use std::convert::TryInto;
use std::ops::{Add, Div, Mul, Neg, Sub};
use rand::Rng;
use unroll::unroll_for_loops;
use crate::{add_no_overflow, cmp, Field, sub, field_to_biguint, rand_range, rand_range_from_rng};
us... | }
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 | import numpy as np
from pyinterpolate.kriging.helper_functions.euclidean_distance import calculate_distance
from pyinterpolate.kriging.helper_functions.euclidean_distance import block_to_block_distances
from pyinterpolate.kriging.helper_functions.euclidean_distance import calculate_block_to_block_distance
# TODO: re... |
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 | import numpy as np
from pyinterpolate.kriging.helper_functions.euclidean_distance import calculate_distance
from pyinterpolate.kriging.helper_functions.euclidean_distance import block_to_block_distances
from pyinterpolate.kriging.helper_functions.euclidean_distance import calculate_block_to_block_distance
# TODO: re... | (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 | import numpy as np
from pyinterpolate.kriging.helper_functions.euclidean_distance import calculate_distance
from pyinterpolate.kriging.helper_functions.euclidean_distance import block_to_block_distances
from pyinterpolate.kriging.helper_functions.euclidean_distance import calculate_block_to_block_distance
# TODO: re... | 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 | import numpy as np
from pyinterpolate.kriging.helper_functions.euclidean_distance import calculate_distance
from pyinterpolate.kriging.helper_functions.euclidean_distance import block_to_block_distances
from pyinterpolate.kriging.helper_functions.euclidean_distance import calculate_block_to_block_distance
# TODO: re... |
# Modeling functions
def poisson_kriging(self, pk_type='centroid'):
"""
:param pk_type: available types:
- 'ata' for area-to-area Poisson Kriging,
- 'atp' for area-to-point Poisson Kriging,
- 'centroid' for centroid based PK.
To run kriging operati... | 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 | package ads
import (
"context"
"strconv"
"strings"
mapset "github.com/deckarep/golang-set"
xds_discovery "github.com/envoyproxy/go-control-plane/envoy/service/discovery/v3"
"github.com/pkg/errors"
"github.com/openservicemesh/osm/pkg/announcements"
"github.com/openservicemesh/osm/pkg/catalog"
"github.com/ope... |
return resourcesRequested
}
// isCNforProxy returns true if the given CN for the workload certificate matches the given proxy's identity.
// Proxy identity corresponds to the k8s service account, while the workload certificate is of the form
// <svc-account>.<namespace>.<trust-domain>.
func isCNforProxy(proxy *envoy... | {
resourcesRequested.Add(discoveryRequest.ResourceNames[idx])
} | conditional_block |
stream.go | package ads
import (
"context"
"strconv"
"strings"
mapset "github.com/deckarep/golang-set"
xds_discovery "github.com/envoyproxy/go-control-plane/envoy/service/discovery/v3"
"github.com/pkg/errors"
"github.com/openservicemesh/osm/pkg/announcements"
"github.com/openservicemesh/osm/pkg/catalog"
"github.com/ope... | (proxy *envoy.Proxy, cn certificate.CommonName) bool {
proxyIdentity, err := catalog.GetServiceAccountFromProxyCertificate(proxy.GetCertificateCommonName())
if err != nil {
log.Error().Err(err).Msgf("Error looking up proxy identity for proxy with SerialNumber=%s on Pod with UID=%s",
proxy.GetCertificateSerialNum... | isCNforProxy | identifier_name |
stream.go | package ads
import (
"context"
"strconv"
"strings"
mapset "github.com/deckarep/golang-set"
xds_discovery "github.com/envoyproxy/go-control-plane/envoy/service/discovery/v3"
"github.com/pkg/errors"
"github.com/openservicemesh/osm/pkg/announcements"
"github.com/openservicemesh/osm/pkg/catalog"
"github.com/ope... | } | random_line_split | |
stream.go | package ads
import (
"context"
"strconv"
"strings"
mapset "github.com/deckarep/golang-set"
xds_discovery "github.com/envoyproxy/go-control-plane/envoy/service/discovery/v3"
"github.com/pkg/errors"
"github.com/openservicemesh/osm/pkg/announcements"
"github.com/openservicemesh/osm/pkg/catalog"
"github.com/ope... |
// isCNforProxy returns true if the given CN for the workload certificate matches the given proxy's identity.
// Proxy identity corresponds to the k8s service account, while the workload certificate is of the form
// <svc-account>.<namespace>.<trust-domain>.
func isCNforProxy(proxy *envoy.Proxy, cn certificate.Common... | {
resourcesRequested := mapset.NewSet()
for idx := range discoveryRequest.ResourceNames {
resourcesRequested.Add(discoveryRequest.ResourceNames[idx])
}
return resourcesRequested
} | identifier_body |
main.py | #!/usr/bin/env python
#
"""
Mindset Meter
The mindset meter will test a users psychometrics and report
their results. These results will also be shared with the
person who invited them to answer the survey.
This file will serve as a prototype of the web based mindsetmeter
meter and develop its api.
bmh October 2012... | .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 | #!/usr/bin/env python
#
"""
Mindset Meter
The mindset meter will test a users psychometrics and report
their results. These results will also be shared with the
person who invited them to answer the survey.
This file will serve as a prototype of the web based mindsetmeter
meter and develop its api.
bmh October 2012... | (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 | #!/usr/bin/env python
#
"""
Mindset Meter
The mindset meter will test a users psychometrics and report
their results. These results will also be shared with the
person who invited them to answer the survey.
This file will serve as a prototype of the web based mindsetmeter
meter and develop its api.
bmh October 2012... |
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 | #!/usr/bin/env python
#
"""
Mindset Meter
The mindset meter will test a users psychometrics and report
their results. These results will also be shared with the
person who invited them to answer the survey.
This file will serve as a prototype of the web based mindsetmeter
meter and develop its api.
bmh October 2012... |
class KeysApi(Handler):
"""Hand out public and private keys"""
def get(self):
keypair = util.Keys().get_pair()
Group.put_group(keypair['private_keys'][0])
self.write_json(keypair)
class ErrorApi(Handler):
"""Log javascript errors for debuggind purposes"""
def post(self):
... | 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 | package proxy
import (
"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()
yamlF... |
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 | package proxy
import (
"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()
yamlF... | (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 | package proxy
import ( | "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 | package proxy
import (
"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()
yamlF... | 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 | //! Adler-32 checksum implementation.
//!
//! This implementation features:
//!
//! - Permissively licensed (0BSD) clean-room implementation.
//! - Zero dependencies.
//! - Decent performance (3-4 GB/s).
//! - `#![no_std]` support (with `default-features = false`).
#![doc(html_root_url = "https://docs.rs/adler/0.2.2")... |
/// 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 | //! Adler-32 checksum implementation.
//!
//! This implementation features:
//!
//! - Permissively licensed (0BSD) clean-room implementation.
//! - Zero dependencies.
//! - Decent performance (3-4 GB/s).
//! - `#![no_std]` support (with `default-features = false`).
#![doc(html_root_url = "https://docs.rs/adler/0.2.2")... | {
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 | //! Adler-32 checksum implementation.
//! | //! - `#![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 | //! Adler-32 checksum implementation.
//!
//! This implementation features:
//!
//! - Permissively licensed (0BSD) clean-room implementation.
//! - Zero dependencies.
//! - Decent performance (3-4 GB/s).
//! - `#![no_std]` support (with `default-features = false`).
#![doc(html_root_url = "https://docs.rs/adler/0.2.2")... | h.write_slice(buf);
buf.len()
};
reader.consume(len);
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::BufReader;
#[test]
fn zeroes() {
assert_eq!(adler32_slice(&[]), 1);
assert_eq!(adler32_slice(&[0]), 1 | 1 << 16);
assert_eq!(adler3... | return Ok(h.checksum());
}
| conditional_block |
main.rs | extern crate rand;
extern crate getopts;
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
extern crate bincode;
extern crate rayon;
pub mod aabb;
pub mod background;
pub mod bvh;
pub mod camera;
pub mod deserialize;
pub mod dielectric;
pub mod disc;
pub mod emitter;
pub mod hitabl... |
//////////////////////////////////////////////////////////////////////////////
// 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 {}",
... | {
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 | extern crate rand;
extern crate getopts;
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
extern crate bincode;
extern crate rayon;
pub mod aabb;
pub mod background;
pub mod bvh;
pub mod camera;
pub mod deserialize;
pub mod dielectric;
pub mod disc;
pub mod emitter;
pub mod hitabl... | (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 | extern crate rand;
extern crate getopts;
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
extern crate bincode;
extern crate rayon;
pub mod aabb;
pub mod background;
pub mod bvh;
pub mod camera;
pub mod deserialize;
pub mod dielectric;
pub mod disc;
pub mod emitter;
pub mod hitabl... |
//////////////////////////////////////////////////////////////////////////////
// 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 | extern crate rand;
extern crate getopts;
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
extern crate bincode;
extern crate rayon;
pub mod aabb;
pub mod background;
pub mod bvh;
pub mod camera;
pub mod deserialize;
pub mod dielectric;
pub mod disc;
pub mod emitter;
pub mod hitabl... | ;
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 | use crate::css::{is_not, CallArgs, CssString, Value};
use crate::error::Error;
use crate::output::{Format, Formatted};
use crate::parser::SourcePos;
use crate::sass::{FormalArgs, Name};
use crate::value::Numeric;
use crate::{sass, Scope, ScopeRef};
use lazy_static::lazy_static;
use std::collections::BTreeMap;
use std::... | (
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 | use crate::css::{is_not, CallArgs, CssString, Value};
use crate::error::Error;
use crate::output::{Format, Formatted};
use crate::parser::SourcePos;
use crate::sass::{FormalArgs, Name};
use crate::value::Numeric;
use crate::{sass, Scope, ScopeRef};
use lazy_static::lazy_static;
use std::collections::BTreeMap;
use std::... | 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 | use crate::css::{is_not, CallArgs, CssString, Value};
use crate::error::Error;
use crate::output::{Format, Formatted};
use crate::parser::SourcePos;
use crate::sass::{FormalArgs, Name};
use crate::value::Numeric;
use crate::{sass, Scope, ScopeRef};
use lazy_static::lazy_static;
use std::collections::BTreeMap;
use std::... |
/// 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 | """
Tic Tac Toe
TODO
* Refactor code to make it more AI tournament-friendly
* ai_move function must only take in game state next time
^ re factor as class? (keep track of game_tree and trash talk flag)
"""
import collections
from functools import partial
import logging
import random
import numpy as np
try:
i... |
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_state)
game_tree[cur_state] = {
... | """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 | """
Tic Tac Toe
TODO
* Refactor code to make it more AI tournament-friendly
* ai_move function must only take in game state next time
^ re factor as class? (keep track of game_tree and trash talk flag)
"""
import collections
from functools import partial
import logging
import random
import numpy as np
try:
i... | (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 | """
Tic Tac Toe
TODO
* Refactor code to make it more AI tournament-friendly
* ai_move function must only take in game state next time
^ re factor as class? (keep track of game_tree and trash talk flag)
"""
import collections
from functools import partial
import logging
import random
import numpy as np
try:
i... | 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 | """
Tic Tac Toe
TODO
* Refactor code to make it more AI tournament-friendly
* ai_move function must only take in game state next time
^ re factor as class? (keep track of game_tree and trash talk flag)
"""
import collections
from functools import partial
import logging
import random
import numpy as np
try:
i... |
def start_game(player1, player2, symbols=("O", "X")):
"""Starts a command line tic tac toe game between 2 players (bot or human)"""
assert len(symbols) == 2, "`symbols` must have exactly 2 elements"
gstate = TicTacToe("_________", symbols=symbols)
with open(GAME_TREE_FILE, "r") as gt_file:
... | print(f"{val} is not a valid value. Please choose from: {choices}") | conditional_block |
web-trader - console.py | # -*- coding: utf-8 -*-
"""
Web-Based Equities Trading System
DATA 602 Assignment 2 / Prof. Jamiel Sheikh
TBD
Created October/November 2017
@author: Ilya Kats
"""
# Required libraries
import urllib.request as req
import pandas as pd
from bs4 import BeautifulSoup
from datetime import datetime
from pymongo import Mon... | ():
'''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 | # -*- coding: utf-8 -*-
"""
Web-Based Equities Trading System
DATA 602 Assignment 2 / Prof. Jamiel Sheikh
TBD
Created October/November 2017
@author: Ilya Kats
"""
# Required libraries
import urllib.request as req
import pandas as pd
from bs4 import BeautifulSoup
from datetime import datetime
from pymongo import Mon... |
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 | # -*- coding: utf-8 -*-
"""
Web-Based Equities Trading System
DATA 602 Assignment 2 / Prof. Jamiel Sheikh
TBD
Created October/November 2017
@author: Ilya Kats
"""
# Required libraries
import urllib.request as req
import pandas as pd
from bs4 import BeautifulSoup | # 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 | # -*- coding: utf-8 -*-
"""
Web-Based Equities Trading System
DATA 602 Assignment 2 / Prof. Jamiel Sheikh
TBD
Created October/November 2017
@author: Ilya Kats
"""
# Required libraries
import urllib.request as req
import pandas as pd
from bs4 import BeautifulSoup
from datetime import datetime
from pymongo import Mon... |
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 | package fs_test
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"errors"
"math/big"
"github.com/sirupsen/logrus"
logrustest "github.com/sirupsen/logrus/hooks/test"
"golang.org/x/crypto/ssh"
boshsysfakes "github.com/cloudfoundry/bosh-utils/system/fakes"
. "github.com/dp... | Config{
CertificatePath: "/path/ca0/certificate",
PrivateKeyPath: "/path/ca0/private_key",
},
&fs,
logger,
)
_, err := subject.GetCertificate()
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("reading certificate"))
})
})
Context("bad cer... | "name1", | random_line_split |
provider_test.go | package fs_test
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"errors"
"math/big"
"github.com/sirupsen/logrus"
logrustest "github.com/sirupsen/logrus/hooks/test"
"golang.org/x/crypto/ssh"
boshsysfakes "github.com/cloudfoundry/bosh-utils/system/fakes"
. "github.com/dp... |
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 | // Package messaging for signing and encryption of messages
package messaging
import (
"crypto/ecdsa"
"crypto/rand"
"crypto/sha256"
"encoding/asn1"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"reflect"
"github.com/iotdomain/iotdomain-go/types"
"github.com/sirupsen/logrus"
"gopkg.in/square/go-jose.v2"... |
sender := reflSender.String()
if sender == "" {
err := errors.New("VerifySenderJWSSignature: Missing sender or address information in message")
return true, err
}
// verify the message signature using the sender's public key
if getPublicKey == nil {
return true, nil
}
publicKey := getPublicKey(sender)
if... | {
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 | // Package messaging for signing and encryption of messages
package messaging
import (
"crypto/ecdsa"
"crypto/rand"
"crypto/sha256"
"encoding/asn1"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"reflect"
"github.com/iotdomain/iotdomain-go/types"
"github.com/sirupsen/logrus"
"gopkg.in/square/go-jose.v2"... | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.