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 |
|---|---|---|---|---|
lib.rs | c >= 'a' && c <= 'f') ||
(c >= 'A' && c <= 'F')
).map(|c| if c >= '0' && c <= '9' {
c as u64 - '0' as u64
} else if c >= 'a' && c <= 'f' {
10 + c as u64 - 'a' as u64
} else {
10 + c as u64 - 'A' as u64
} as u32
)
}
fn unicode_char<'a>() -> imp... | <'a>() -> impl Parser<&'a str, Output = Node> {
c_hx_do!{
word <- string("true").or(string("false"));
match word {
"true" => Node::Boolean(true),
_ => Node::Boolean(false)
}
}
}
fn null_parser<'a>() -> impl Parser<&'a str, Output = Node> {
c_hx_do!{
_... | bool_parser | identifier_name |
main.rs | : Some("demo Company"),
// model_number: None,
// serial_number: None,
// system_id: Some("sysid69"),
// ieee_cert: None,
// hw_revision: None,
// sw_revision: None,
// pnp_id: None
// };
//
#[entry]
fn entry() -> ! {
//rtt_init_print!(BlockIfFull, 4096);
rtt_init_print!(NoBlockSkip... | extended_packet_length_enable: 1,
pr_write_list_size: 0x3A,
mb_lock_count: 0x79,
att_mtu: 312,
slave_sca: 500,
master_sca: 0,
ls_source: 1,
max_conn_event_length: 0xFFFFFFFF,
hs_startup_time: 0x148,
viterbi_enable: 1,
ll_only: 0,
... | num_attr_serv: 10,
attr_value_arr_size: 3500, //2788,
num_of_links: 8, | random_line_split |
main.rs | : Some("demo Company"),
// model_number: None,
// serial_number: None,
// system_id: Some("sysid69"),
// ieee_cert: None,
// hw_revision: None,
// sw_revision: None,
// pnp_id: None
// };
//
#[entry]
fn entry() -> ! {
//rtt_init_print!(BlockIfFull, 4096);
rtt_init_print!(NoBlockSkip... | else {
rprintln!("Unexpected response to init_gap command");
return Err(());
};
perform_command(|rc| {
rc.update_characteristic_value(&UpdateCharacteristicValueParameters {
service_handle,
characteristic_handle: dev_name_handle,
offset: 0,
... | {
(service_handle, dev_name_handle, appearance_handle)
} | conditional_block |
main.rs | = ShciBleInitCmdParam {
p_ble_buffer_address: 0,
ble_buffer_size: 0,
num_attr_record: 100,
num_attr_serv: 10,
attr_value_arr_size: 3500, //2788,
num_of_links: 8,
extended_packet_length_enable: 1,
pr_write_list_size: 0x3A,
mb_lock_count: 0x79,
... | get_bd_addr | identifier_name | |
main.rs | | {
rc.set_discoverable(&DISCOVERY_PARAMS)
.map_err(|_| nb::Error::Other(()))
})
.expect("Failed to enable discoverable mode again");
// perform_command(|rc| {
// rc.update_advertisin... | {
EncryptionKey(BLE_CFG_ERK)
} | identifier_body | |
main.rs | (x : &String) -> &str {
let bytes = x.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &x[0..i];
}
}
&x[..]
}
fn second_word(x : &String) -> &str {
let mut bytes = x.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' '{
let y = &x[i+1..];
byt... | first_word | identifier_name | |
main.rs |
fn second_word(x : &String) -> &str {
let mut bytes = x.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' '{
let y = &x[i+1..];
bytes = y.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &y[0..i];
}
}
// Return this IF there were ... | {
let bytes = x.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &x[0..i];
}
}
&x[..]
} | identifier_body | |
main.rs | &x[..]
}
fn second_word(x : &String) -> &str {
let mut bytes = x.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' '{
let y = &x[i+1..];
bytes = y.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &y[0..i];
}
}
// Return this IF th... | random_line_split | ||
main.rs |
}
&x[..]
}
//__________________________________________________________________________________________________________ //
//--------------------------------------------------//
//*** GENERAL NOTES ***
//*** Info: Random Notes I found either important, ***
//*** hard to remember, funny, coo... | {
let y = &x[i+1..];
bytes = y.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &y[0..i];
}
}
// Return this IF there were only two words.
return &y[..];
} | conditional_block | |
SocialSpiderAlgorithm.py | .exp((-distance(pa.s, pb.s))/(ra * sd))
# Calculate Standard_Deviation σ along each dimension
def standard_deviation():
pop = [spider.s for spider in spiders]
return np.sum(np.std(pop, axis=1)) / n
def f(a):
z = []
if Minimize_problem:
z.extend(a)
return eval(y)
elif Maximize_pro... | # Calculate the intensity of the vibrations V
# generated by all spiders and Select the strongest vibration
sd = standard_deviation()
for x in range(population):
max_vibration = Vibration(np.zeros(n), -1)
for t in range(population):
if x != t:
... | lobal spiders
spiders = []
create_population_of_spiders()
minimize = spiders[0].s
number_of_iterations = 0
initialization_graphics(graph)
# In the iteration phase
while number_of_iterations <= lim:
# Calculates the fitness , update the global optimum and generate vibrations
g... | identifier_body |
SocialSpiderAlgorithm.py | .exp((-distance(pa.s, pb.s))/(ra * sd))
# Calculate Standard_Deviation σ along each dimension
def standard_deviation():
pop = [spider.s for spider in spiders]
return np.sum(np.std(pop, axis=1)) / n
def f | a):
z = []
if Minimize_problem:
z.extend(a)
return eval(y)
elif Maximize_problem:
z.extend(-a)
return -eval(y)
# there is a array with 100 elements with one and zero,100*p elements with 0 , 100(1-p) with 1,0=false,1=true
# where p is the probability
def probability(p):
... | ( | identifier_name |
SocialSpiderAlgorithm.py | ("spider" + str(x))
spiders[x].printout()
print("generate vibration = " + str(generate_vibration[x].intensity))
print("")
# if return true then it is out of bounds [a,b]
def out_of_bounds(position):
for x in range(len(position)):
if position[x] < bounds[x, 0] or position[x] > bound... | random_line_split | ||
SocialSpiderAlgorithm.py | .exp((-distance(pa.s, pb.s))/(ra * sd))
# Calculate Standard_Deviation σ along each dimension
def standard_deviation():
pop = [spider.s for spider in spiders]
return np.sum(np.std(pop, axis=1)) / n
def f(a):
z = []
if Minimize_problem:
z.extend(a)
return eval(y)
elif Maximize_pro... | else:
return False
def show(generate_vibration):
for x in range(population):
print("")
print("spider" + str(x))
spiders[x].printout()
print("generate vibration = " + str(generate_vibration[x].intensity))
print("")
# if return true then it is out of bounds [a,b... | eturn True
| conditional_block |
__init__.py | return group_config
def init(self):
"""
called after the plugin is initialized, plugin may define this for any
other initialization code
"""
pass
def on_start(self):
"""
called when the daemon is starting
"""
pass
def on_stop(self)... | If it doesnt, because file has been deleted, we close
the filehander and try to reopen
"""
if self.fh.closed:
try:
self.fh = open(self.path, "r")
self.fh.seek(0, 2)
except OSError as err:
logging.error("Could not reo... | random_line_split | |
__init__.py | """
logger instance for plugin type
"""
if not self._logger:
self._logger = logging.getLogger('vaping.plugins.' + self.plugin_type)
return self._logger
def __init__(self, config, ctx):
"""
**Arguments**
- config (`dict`)
- ctx: vaping co... | get | identifier_name | |
__init__.py | return group_config
def init(self):
"""
called after the plugin is initialized, plugin may define this for any
other initialization code
"""
pass
def on_start(self):
"""
called when the daemon is starting
"""
pass
def on_stop(self)... |
emit = self._emit_queue.get()
emit()
def emit_all(self):
"""
emit and remove all emissions in the queue
"""
while not self._emit_queue.empty():
self.send_emission()
class TimedProbe(ProbeBase):
"""
Probe class that calls probe every config defi... | return | conditional_block |
__init__.py | return group_config
def init(self):
"""
called after the plugin is initialized, plugin may define this for any
other initialization code
"""
pass
def on_start(self):
"""
called when the daemon is starting
"""
pass
def on_stop(self)... |
@abc.abstractmethod
def emit(self, message):
""" accept message to emit """
class TimeSeriesDB(EmitBase):
"""
Base interface for | super(EmitBase, self).__init__(config, ctx) | identifier_body |
integratedAnalysisPipeline.py | (stringFind,configFile):
"""findPath will find path or value of associated specified string or info from config file"""
for line in configFile:
if stringFind in line: # if find string specified, return pathname or specific value trying to find
configFile.seek(0)
return line.split... | parseConfigFindPath | identifier_name | |
integratedAnalysisPipeline.py | OutPath, BPsThreshold, multipleSeqAlignFastasPath,
fastaOutputName, allMAPImageOutputPath, online, projectName, nerscUsername, nohup, cactusRun,cactusFolder) = tuple(findInfoList)
# for debugging, see if all of your data has passed through
print tuple(findInfoList)
# generate weights file for allmaps...
open('%swe... | try:
int(BPsMergeDist)
except:
BPsMergeDist = '100000'
# write syntenic Config text
generateIntAnalysisConfig('syntenyAnalysis',(NameAnalysis,writeFastaOut,Loci_Threshold,pathPython,pathUnOut,pathSort, BPsMergeDist,softmask,
NameAnalysis,multipleSeqAlignFastasPath,s... | random_line_split | |
integratedAnalysisPipeline.py | %querySpecies+weight+'\n')
weightsFile.close()
#fake473_283 1
# generate config files
# first need to generate 3 syntenic files list and list of genome files for synteny analysis
# second generate faiFiles list and bed files list circos
# third generate bedfile list and fastainputname
# get list of genome files, fai ... | print 'circos'
# try to run circos online
if int(online):
open('runCircos.sh', 'w').close()
# writing shell script to run circos
circos = open('runCircos.sh', 'w')
circos.write('#!/bin/bash\npython circosFiguresPipeline.py')
circos.close()
try:
# try t... | conditional_block | |
integratedAnalysisPipeline.py |
def parseConfigFindPath(stringFind,configFile):
"""findPath will find path or value of associated specified string or info from config file"""
for line in configFile:
if stringFind in line: # if find string specified, return pathname or specific value trying to find
configFile.seek(0)
... | """parseConfigFindList inputs a particular string to find and read file after and a configuration file object
outputs list of relevant filenames"""
read = 0
listOfItems = []
for line in configFile:
if line:
if read == 1:
if 'Stop' in line:
configFi... | identifier_body | |
vector_test.go | (t *testing.T) {
var i, j uint
for i = 0; i < 100; i++ {
randslice := makeRandSlice(i)
v := NewFrom(randslice)
if v.Dim() != i {
t.Errorf("Wrong dimension. Got %d, expected %d.", v.Dim(), i)
}
for j = 0; j < i; j++ {
val, _ := v.Get(j)
if val != randslice[j] {
t.Error(
"Wrong values in vec... | TestNewFrom | identifier_name | |
vector_test.go | < 100; i++ {
randslice := makeRandSlice(i)
v := NewFrom(randslice)
if v.Dim() != i {
t.Errorf("Wrong dimension. Got %d, expected %d.", v.Dim(), i)
}
for j = 0; j < i; j++ {
val, _ := v.Get(j)
if val != randslice[j] {
t.Error(
"Wrong values in vector initialized from a random slice.")
}
... | // then as an in-place operations, checking if both operation were correct.
func TestAdd(t *testing.T) {
var i, j uint
for i = 1; i < 100; i++ {
a := makeRandomVector(i)
b := makeRandomVector(i)
c, _ := Add(a, b)
for j = 0; j < i; j++ {
if c.dims[j] != a.dims[j]+b.dims[j] {
t.Error("Addition failed, d... | // =========================== [ Operation Tests ] ============================
// Creates pesudo-random vectors, then adds them first as a non-destructive, | random_line_split |
vector_test.go | 0)
if Equal(v, w) {
t.Error("Equal() == true for unequal vectors.")
}
}
// =========================== [ Operation Tests ] ============================
// Creates pesudo-random vectors, then adds them first as a non-destructive,
// then as an in-place operations, checking if both operation were correct.
func Test... | , length)
for i := range randslice {
randslice[i] = rand.ExpFloat64()
}
return
}
// Helper function, make a | identifier_body | |
vector_test.go | 100; i++ {
randslice := makeRandSlice(i)
v := NewFrom(randslice)
if v.Dim() != i {
t.Errorf("Wrong dimension. Got %d, expected %d.", v.Dim(), i)
}
for j = 0; j < i; j++ {
val, _ := v.Get(j)
if val != randslice[j] {
t.Error(
"Wrong values in vector initialized from a random slice.")
}
}... |
}
// =========================== [ Operation Tests ] ============================
// Creates pesudo-random vectors, then adds them first as a non-destructive,
// then as an in-place operations, checking if both operation were correct.
func TestAdd(t *testing.T) {
var i, j uint
for i = 1; i < 100; i++ {
a := make... | {
t.Error("Equal() == true for unequal vectors.")
} | conditional_block |
preprocessing.py | = pd.DataFrame(data=x_train, columns=dataset.columns[1:-1])
train["Trend"] = pd.Series(y_train)
# Do the same for x_test and y__test
test = pd.DataFrame(data=x_test, columns=dataset.columns[1:-1])
test["Trend"] = pd.Series(y_test)
# Apply random undersampling to both data frames
train_downsampled = random_unde... | print("\tAdding lag variables")
new_df_dict = {}
for col_header in dataset.drop(["Date", "Trend"], axis=1):
new_df_dict[col_header] = dataset[col_header]
for lag in range(1, lag + 1):
new_df_dict["%s_lag%d" % (col_header, lag)] = dataset[col_header].shift(-lag)
new_df = pd.DataFrame(new_df_dict, index=datas... | identifier_body | |
preprocessing.py | = train_downsampled.drop(["Trend"], axis=1).values
test_trimmed = test_downsampled.drop(["Trend"], axis=1).values
return train_trimmed, test_trimmed, train_trend, test_trend
def unbalanced_split(dataset, test_size):
"""Randomly splits dataset into unbalanced training and test sets."""
print("\tSplitting data in... | if balanced:
return balanced_split(dataset, test_size)
else:
return unbalanced_split(dataset, test_size) | random_line_split | |
preprocessing.py | impson_est.append(simps(x, dx=1))
dead_values = list([None] * interval)
dead_values.extend(integral_simpson_est)
dead_values.reverse()
return dead_values
def random_undersampling(dataset):
"""Randomly deleting rows that contain the majority class until the number
in the majority class is equal with the number ... | calculate_sentiment | identifier_name | |
preprocessing.py | ):
minority_set, majority_set = majority_set, minority_set
# Downsample majority class
majority_downsampled = resample(majority_set,
replace=False, # sample without replacement
n_samples=len(minority_set), # to match minority class
... | numer += (nextRow["Sentiment"] * nextRow["Tweets"])
denom += nextRow["Tweets"] | conditional_block | |
networking.go | a newline.
The STRING command includes one line of string
data, which can be handled by simple read and write methods from `bufio`.
The GOB command comes with a `struct` that contains a couple of fields,
including a slice, a map, and a even a pointer to itself. As you can see when
running the code, the `gob` ... | {
return errors.Wrap(err, "Could not send additional STRING data ("+strconv.Itoa(n)+" bytes written)")
} | conditional_block | |
networking.go | package, this requires no efforts. The following
animation shows how gob data gets from a client to a server, and when
this looks quite unspectacular, it's because using `gob` *is* unspectacular.
HYPE[Sending a struct as GOB](gob.html)
It's not much more than that!
## Basic ingredients for sending string ... | * It dispatches incoming commands to the associated handler based on the commands
name.
*/
// HandleFunc is a function that handles an incoming command.
// It receives the open connection wrapped in a `ReadWriter` interface.
type HandleFunc func(*bufio.ReadWriter)
// Endpoint provides an endpoint to other... | The nature of the data depends on the respective command. To handle this, we
create an `Endpoint` object with the following properties:
* It allows to register one or more handler functions, where each can handle a
particular command.
| random_line_split |
networking.go | }
return bufio.NewReadWriter(bufio.NewReader(conn), bufio.NewWriter(conn)), nil
}
/*
## Incoming connections
Preparing for incoming data is a bit more involved. According to our ad-hoc
protocol, we receive the name of a command terminated by `\n`, followed by data.
The nature of the data depends on the resp... | {
connect := flag.String("connect", "", "IP address of process to join. If empty, go into listen mode.")
flag.Parse()
// If the connect flag is set, go into client mode.
if *connect != "" {
err := client(*connect)
if err != nil {
log.Println("Error:", errors.WithStack(err))
}
log.Println("Clie... | identifier_body | |
networking.go | it uses the port associated with that service.
For example, Web servers usually listen on port 80 for HTTP requests and
on port 443 for HTTPS requests. SSH daemons listen on port 22 by default,
and a WHOIS server uses port 43.
The core parts of the `net` package for implementing the server side are:
`net.List... | client | identifier_name | |
model_seq.py | y in y_pred:
# y_fixed = decode_labels(y)
# temp_pred.append(y_fixed)
# y_pred = temp_pred
# Convert crf output to xml tags
test_dict = {}
for x in range(len(test_ids)):
rec_id = test_ids[x]
rec_seq = zip((item[0] for item in test_seqs[x]), y_pred_labels[x])
... | time_seq.append(lab)
event_seq.append('O') | conditional_block | |
model_seq.py | y_time)
#y_pred_time = predict_seqs(time_encoder_model, time_decoder_model, testx)
#testy_labels_time = []
#for seq in testy_time:
# testy_labels_time.append(decode_labels(seq))
#testy_time = testy_labels_time
#event_model, event_encoder_model, event_decoder_model = t... | (encoder_model, decoder_model, testx, output_seq_len, output_dim, vec_labels=False):
testy_pred = []
print "output_seq_len: " + str(output_seq_len)
print "output_dim: " + str(output_dim)
print "vec_labels: " + str(vec_labels)
for test_seq in testx:
input_seq = []
input_seq.append(tes... | predict_seqs | identifier_name |
model_seq.py | label_set
label_set = set([])
for s in seqs:
s_feats = []
s_labels = []
for pair in s:
word = pair[0]
vector = word2vec.get(word, vec_model)
s_feats.append(vector)
s_labels.append(pair[1])
label_set.add(pair[1])
feats.a... | return [label for token, label in sent] | identifier_body | |
model_seq.py | _score(testy, y_pred, average='weighted', labels=labels)
print "F1: " + str(f1_score)
sorted_labels = sorted(labels, key=lambda name: (name[1:], name[0]))
print(metrics.flat_classification_report(testy, y_pred, labels=sorted_labels, digits=3))
return f1_score
def split_labels(y):
t_labels = ['BT', ... | 'word.isdigit()': word.isdigit(),
#'postag': postag, | random_line_split | |
ChoiceSet.js | *
* @param {Array<Object>} n-number of Objects as described in the
* constructor reference. There should be at least a name property
* and a value property.
*/
static of(...values)
{
let array =
values.length === 1 &&
values[0] instanceof Array &&
values[0] || values;
c... |
/**
* Simulates rolling dice with n-number of sides. In pen and paper
* role-playing games, 3d6 means to roll three six sided dice together
* and sum their results. Calling ChoiceSet.rollDice(3, 6) will simulate
* the same effect.
*
* Optionally, if repeat is set to a number greater than 1, an arr... | {
let choices = [];
for (let i = 0; i < count; i++) {
choices.push(this.chooseProp(prop))
}
return choices;
} | identifier_body |
ChoiceSet.js | *
* @param {Array<Object>} n-number of Objects as described in the
* constructor reference. There should be at least a name property
* and a value property.
*/
static of(...values)
{
let array =
values.length === 1 &&
values[0] instanceof Array &&
values[0] || values;
c... | }
/**
* Allows easy adjustment of a weight for a given index. The weight is
* modified and then calcIntervals() is called to realign things for
* the next choosing.
*
* NOTE see if this is the optimal setting for adjusting the weights
*
* @param {Number} index the index of the choice to modify... | return cur + array.slice(0,idx).reduce((p, c) => p + c, 0);
});
this.intervals = intervals;
this.maxInterval = intervals[intervals.length - 1]; | random_line_split |
ChoiceSet.js | = from; i < (to + 1); i++) {
set.choices.push({
name: i,
weight: 100
});
}
if (weights)
{
set.setWeights(weights);
}
else {
set.calcIntervals();
}
return set;
}
/**
* An easy way to instantiate a ChoiceSet of names and values. The
* funct... | {
index = i;
break;
} | conditional_block | |
ChoiceSet.js | *
* @param {Array<Object>} n-number of Objects as described in the
* constructor reference. There should be at least a name property
* and a value property.
*/
static of(...values)
{
let array =
values.length === 1 &&
values[0] instanceof Array &&
values[0] || values;
c... | (prop = 'name')
{
return this.chooseProp(prop);
}
/**
* Returns an array of results equivalent to those returned by
* chooseOne.
*
* @param {Number} count an integer denoting the number of choices to pick
* @param {String} prop the property of the randomly chosen item
* @return {Mixed} the ... | chooseOne | identifier_name |
canvas.go | .size.X*c.size.Y)
c.visited = make([]bool, c.size.X*c.size.Y)
for y, line := range lines {
x := 0
for len(line) > 0 {
r, l := utf8.DecodeRune(line)
c.grid[y*c.size.X+x] = char(r)
x++
line = line[l:]
}
for ; x < c.size.X; x++ {
c.grid[y*c.size.X+x] = ' '
}
}
c.findObjects()
return c, nil
... |
// findObjects finds all objects (lines, polygons, and text) within the underlying grid.
func (c *canvas) findObjects() {
p := Point{}
// Find any new paths by starting with a point that wasn't yet visited, beginning at the top
// left of the grid.
for y := 0; y < c.size.Y; y++ {
p.Y = y
for x := 0; x < c.si... | {
maxTL := Point{X: -1, Y: -1}
var q []Object
for _, o := range c.objects {
// An object can't really contain another unless it is a polygon.
if !o.IsClosed() {
continue
}
if o.HasPoint(p) && o.Corners()[0].X > maxTL.X && o.Corners()[0].Y > maxTL.Y {
q = append(q, o)
maxTL.X = o.Corners()[0].X
... | identifier_body |
canvas.go | // paths (either open or closed) are found.
c.visit(p)
objs := c.scanPath([]Point{p})
for _, obj := range objs {
// For all points in all objects found, mark the points as visited.
for _, p := range obj.Points() {
c.visit(p)
}
}
c.objects = append(c.objects, objs...)
}
... | obj.SetTag(t)
c.options[t] = m.(map[string]interface{})
} | random_line_split | |
canvas.go | ch := c.at(p); ch.isTextStart() {
obj := c.scanText(p)
// scanText will return nil if the text at this area is simply
// setting options on a container object.
if obj == nil {
continue
}
for _, p := range obj.Points() {
c.visit(p)
}
c.objects = append(c.objects, obj)
}
}... | unvisit | identifier_name | |
canvas.go | .size.X*c.size.Y)
c.visited = make([]bool, c.size.X*c.size.Y)
for y, line := range lines {
x := 0
for len(line) > 0 {
r, l := utf8.DecodeRune(line)
c.grid[y*c.size.X+x] = char(r)
x++
line = line[l:]
}
for ; x < c.size.X; x++ {
c.grid[y*c.size.X+x] = ' '
}
}
c.findObjects()
return c, nil
... |
return objs
}
// The next returns the points that can be used to make progress, scanning (in order) horizontal
// progress to the left or right, vertical progress above or below, or diagonal progress to NW,
// NE, SW, and SE. It skips any points already visited, and returns all of the possible progress
// points.
fu... | {
if c.isVisited(n) {
continue
}
c.visit(n)
p2 := make([]Point, len(points)+1)
copy(p2, points)
p2[len(p2)-1] = n
objs = append(objs, c.scanPath(p2)...)
} | conditional_block |
client.rs | fn new(reader: R, writer: W, rng: OsRng) -> TlsResult<TlsClient<R, W>> {
let mut client = TlsClient {
reader: TlsReader::new(reader),
writer: TlsWriter::new(writer),
rng: rng,
buf: Vec::new(),
};
// handshake failed. send alert if necessary
... | write_all | identifier_name | |
client.rs | <R>,
pub writer: TlsWriter<W>,
pub rng: OsRng,
buf: Vec<u8>,
}
impl<R: Read, W: Write> TlsClient<R, W> {
pub fn new(reader: R, writer: W, rng: OsRng) -> TlsResult<TlsClient<R, W>> {
let mut client = TlsClient {
reader: TlsReader::new(reader),
writer: TlsWriter::new(write... | try!(self.writer.write_handshake(&client_key_exchange));
try!(self.writer.write_change_cipher_spec());
// SECRET
let master_secret = {
let mut label_seed = b"master secret".to_vec();
label_seed.extend(&cli_random);
label_seed.extend(&server_hello_dat... | random_line_split | |
client.rs | ) -> &mut W {
self.writer.get_mut()
}
// this does not send alert when error occurs
fn handshake(&mut self) -> TlsResult<()> {
// expect specific HandshakeMessage. otherwise return Err
macro_rules! expect {
($var:ident) => ({
match try!(self.reader.read_h... | {
to.write(from).unwrap()
} | identifier_body | |
analysis.py | object and returns a matrix with each
column normalized so its minimum value is mapped to zero and its maximum value is mapped to 1."""
column_matrix=data.get_data(headers)
column_max=column_matrix.max(1)
column_min=column_matrix.min(1)
range=column_max-column_min
nomalized=(column_matrix-column_min)/range
ret... | (A, means):
# set up some useful constants
MIN_CHANGE = 1e-7
MAX_ITERATIONS = 100
D = means.shape[1]
K = means.shape[0]
N = A.shape[0]
# iterate no more than MAX_ITERATIONS
for i in range(MAX_ITERATIONS):
# calculate the codes
codes, errors = kmeans_classify( A, | kmeans_algorithm | identifier_name |
analysis.py |
column_max=column_matrix.max(1)
column_min=column_matrix.min(1)
final=np.concatenate((column_min, column_max), axis=1)
rng=final.tolist()
return rng
def mean(headers, data):
""" Takes in a list of column headers and the Data object and returns a list of the
mean values for each column. Use the built-in num... | print "wrong headers, not present in data Object"
return [] | conditional_block | |
analysis.py | and the Data object and returns a matrix with each
column normalized so its minimum value is mapped to zero and its maximum value is mapped to 1."""
column_matrix=data.get_data(headers)
column_max=column_matrix.max(1)
column_min=column_matrix.min(1)
range=column_max-column_min
nomalized=(column_matrix-column_mi... | index=index+1
#the projected data
pdata=np.dot(V,(D.T))
pdata=pdata.T
pcad=data.PCAData(headers,pdata,S,V,m)
return pcad
def kmeans_numpy( d, headers, K, whiten = True):
'''Takes in a Data object, a set of headers, and the number of clusters to create
Computes and returns the codebook, codes, and repre... | e=(d*d)/(U.shape[0]-1)
S[index]=e | random_line_split |
analysis.py | object and returns a matrix with each
column normalized so its minimum value is mapped to zero and its maximum value is mapped to 1."""
column_matrix=data.get_data(headers)
column_max=column_matrix.max(1)
column_min=column_matrix.min(1)
range=column_max-column_min
nomalized=(column_matrix-column_min)/range
ret... |
"""
def kmeans_algorithm(A, means):
# set up some useful constants
MIN_CHANGE = 1e-7
MAX_ITERATIONS = 100
D = means.shape[1]
K = means.shape[0]
N = A.shape[0]
# iterate no more than MAX_ITERATIONS
for i in range(MAX_ITERATIONS):
# calculate the codes
codes, errors = kmeans_classify( A, means )
# calcu... | ID=[] # list of ID values
mindistances=[] # minimum distances algorithm
for dpoint in d:
distances=[] # distances from each mean
for mean in means: # compute distance of each mean, using the distance formula
differences=dpoint-mean
squares=np.square(differences)
sums=np.sum(squares)
distance=np.sqr... | identifier_body |
bundle.js | 0 * placeIndex;
if (days.value == '' || people.value == '' || days.value == '0' || people.value == '0'){
totalOutput.innerHTML = 0;
} else {
totalOutput.innerHTML = totalSum;
}
});
days.addEventListener('blur', function(){
daysSum = +this.value;
totalSum = (peopleSum + daysSu... | function | identifier_name | |
bundle.js | && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, functi... | lassList.contains('hide')){
tabContent[b].classList.remove('hide');
tabContent[b].classList.add('show');
}
}
// attaching EventListener to the parent using delegetion
| identifier_body | |
bundle.js | namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode ... |
});
days.addEventListener('blur', function(){
daysSum = +this.value;
totalSum = (peopleSum + daysSum) * 4000 * placeIndex;
if (days.value == '' || people.value == '' || days.value == '0' || people.value == '0'){
totalOutput.innerHTML = 0;
} else {
totalOutput.innerHTML = totalSu... | {
totalOutput.innerHTML = totalSum;
} | conditional_block |
bundle.js | {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasO... | random_line_split | ||
codec.rs | ());
}
}
}
}
}
impl<EncodeFn, Item> Encode<Item> for EncodeFn
where
EncodeFn: Fn(&Item, &mut BytesMut),
{
fn encode(&mut self, item: &Item, buffer: &mut BytesMut) {
self(item, buffer)
}
}
//
// Implementer's notes: We store future values in `Source` and `Sin... | fn encode(item: &String, buffer: &mut BytesMut) { | random_line_split | |
codec.rs | : &mut BytesMut);
}
// TODO: We intend to implement `Decode` for async functions, similar to what we do for `Encode`.
// However, for unknown reasons, it is causing the compiler to crash. Currently, we are only able
// to provide an implementation for non-async functions.
#[async_trait]
impl<Stream, DecodeFn, Item, E... | {
if buffer.remaining() < 1 {
return Ok(None);
}
let size = usize::from(buffer[0]);
if buffer.remaining() < 1 + size {
return Ok(None);
}
let mut vec = vec![0u8; size];
buffer.get_u8();
buffer.copy_to_slice(&mut vec);
Ok(Som... | identifier_body | |
codec.rs | a stream item and writes the output to a byte stream buffer.
fn encode(&mut self, item: &Item, buffer: &mut BytesMut);
}
// TODO: We intend to implement `Decode` for async functions, similar to what we do for `Encode`.
// However, for unknown reasons, it is causing the compiler to crash. Currently, we are only a... | (&mut self, stream: &mut Stream) -> Result<Option<Self::Item>, Self::Error> {
loop {
if let Some(item) = self(&mut stream.buffer())? {
return Ok(Some(item));
}
if stream.recv_or_eof().await?.is_none() {
if stream.buffer().is_empty() {
... | decode | identifier_name |
issued_certificate.pb.go | ,json=issuedCertificateSecret,proto3" json:"issued_certificate_secret,omitempty"`
// A ref to a PodBounceDirective specifying a list of k8s pods to bounce
// (delete and cause a restart) when the certificate is issued.
// This will include the control plane pods as well as any pods
// which share a data plane with ... | func (m *IssuedCertificateSpec) XXX_Merge(src proto.Message) {
xxx_messageInfo_IssuedCertificateSpec.Merge(m, src)
}
func (m *IssuedCertificateSpec) XXX_Size() int {
return xxx_messageInfo_IssuedCertificateSpec.Size(m)
}
func (m *IssuedCertificateSpec) XXX_DiscardUnknown() {
xxx_messageInfo_IssuedCertificateSpec.Dis... | random_line_split | |
issued_certificate.pb.go | =issuedCertificateSecret,proto3" json:"issued_certificate_secret,omitempty"`
// A ref to a PodBounceDirective specifying a list of k8s pods to bounce
// (delete and cause a restart) when the certificate is issued.
// This will include the control plane pods as well as any pods
// which share a data plane with the t... |
func init() {
proto.RegisterFile("github.com/solo-io/gloo-mesh/api/certificates/issued_certificate.proto", fileDescriptor_86ade12c22739639)
}
var fileDescriptor_86ade12c22739639 = []byte{
// 479 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x53, 0x5d, 0x... | {
proto.RegisterEnum("certificates.mesh.gloo.solo.io.IssuedCertificateStatus_State", IssuedCertificateStatus_State_name, IssuedCertificateStatus_State_value)
proto.RegisterType((*IssuedCertificateSpec)(nil), "certificates.mesh.gloo.solo.io.IssuedCertificateSpec")
proto.RegisterType((*IssuedCertificateStatus)(nil), "... | identifier_body |
issued_certificate.pb.go | =issuedCertificateSecret,proto3" json:"issued_certificate_secret,omitempty"`
// A ref to a PodBounceDirective specifying a list of k8s pods to bounce
// (delete and cause a restart) when the certificate is issued.
// This will include the control plane pods as well as any pods
// which share a data plane with the t... | () string {
if m != nil {
return m.Org
}
return ""
}
func (m *IssuedCertificateSpec) GetSigningCertificateSecret() *v1.ObjectRef {
if m != nil {
return m.SigningCertificateSecret
}
return nil
}
func (m *IssuedCertificateSpec) GetIssuedCertificateSecret() *v1.ObjectRef {
if m != nil {
return m.IssuedCerti... | GetOrg | identifier_name |
issued_certificate.pb.go | 0xef, 0x09, 0x14, 0x68, 0x4b, 0x5e, 0x55, 0xf5, 0xe9, 0xe8, 0x67, 0x8b, 0x3c, 0x0f, 0xad,
0xe0, 0xf7, 0x7f, 0xc5, 0xc5, 0x05, 0x64, 0xb4, 0x47, 0x3a, 0x4b, 0xd4, 0x46, 0x7b, 0xce, 0xb0,
0x3d, 0xee, 0x46, 0x75, 0x43, 0x5d, 0xd2, 0x46, 0x25, 0xbc, 0xd6, 0xd0, 0x19, 0x77, 0xa3, 0xaa,
0xa4, 0x37, 0xa4, 0xaf, 0xa5, 0xd8,... | {
return false
} | conditional_block | |
mprocessing.py | function to run function in multiprocessing mode
"""
# -----------------------------------------------------------------------------
# Import section for Python 2 and 3 compatible code
# from __future__ import absolute_import, division, print_function,
# unicode_literals
from __future__ import division # This w... |
else:
# Control for when running multiprocessing release locking
logging.debug('===Multiprocessing=== <--[ ].lock.release')
try:
adb_lock.release()
use_dblock_return = True
except Exception:
NPR.niceerror(caught=Tru... | logging.debug('===Multiprocessing=== -->[ ].lock.acquire')
try:
if adb_lock.acquire():
use_dblock_return = True
except Exception:
NPR.niceerror(caught=True,
caughtprefix='+++ ',
caught... | conditional_block |
mprocessing.py | Helper function to run function in multiprocessing mode
"""
# -----------------------------------------------------------------------------
# Import section for Python 2 and 3 compatible code
# from __future__ import absolute_import, division, print_function,
# unicode_literals
from __future__ import division #... | return use_dblock_return
logging.debug('use_lock: adb_lock.semlock:[%s].', adb_lock._semlock)
if operation is None:
return use_dblock_return
if (nprocs is not None) and (nprocs) and (nprocs > 0):
if operation:
# Control for when running multiprocessing set locking
... | """ use_lock
adb_lock = lock to be used
operation = True => Lock
= False => Release
nprocs = >0 when in multiprocessing mode
>>> alock = multiprocessing.Lock()
>>> use_lock(alock, True, 2)
True
>>> use_lock(alock, False, 2)
True
... | identifier_body |
mprocessing.py | function to run function in multiprocessing mode
"""
# -----------------------------------------------------------------------------
# Import section for Python 2 and 3 compatible code
# from __future__ import absolute_import, division, print_function,
# unicode_literals
from __future__ import division # This w... | logger = multiprocessing.get_logger()
logger.setLevel(log_level)
logging.debug('===Multiprocessing=== Logging defined!')
# ---------------------------------------------------------
# chunk
#
# Divides an iterable in slices/chunks of size size
#
def chunk(iter_list, size):
"... | # CODING No need for such low level debugging to stderr
# multiprocessing.log_to_stderr() | random_line_split |
mprocessing.py | function to run function in multiprocessing mode
"""
# -----------------------------------------------------------------------------
# Import section for Python 2 and 3 compatible code
# from __future__ import absolute_import, division, print_function,
# unicode_literals
from __future__ import division # This w... | (nprocs, lockdb, running, mutex, itemslist, a_fn, cur):
""" mprocessing Function
nprocs = Number of processes to launch (int)
lockdb = lock for access to Database (lock obj to be created)
running = Value to count processed items (count obj to be created)
mutex ... | mprocessing | identifier_name |
aes.rs | 1b4ef5bcb3e92e21123e951cf6f8f188e"
),
expand_key(&vec![0; 16])
);
assert_eq!(
parse_byte_string(
"ffffffffffffffffffffffffffffffffe8e9e9e917161616e8e9e9e917161616adaeae19bab8b80f525151e6454747f0090e2277b3b69a78e1e7cb9ea4a08c6ee16abd3e52dc2746b33becd8179b60b6e5baf3ceb766d488045d385013c658e671d07db3... | {
let mut rows = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
shift_rows(&mut rows);
assert_ne!(
rows,
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
);
inv_shift_rows(&mut rows);
assert_eq!(
rows,
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
);
} | identifier_body | |
aes.rs | 0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49, 0x6D, 0x8B, 0xD1, 0x25,
0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92,
0x6C, 0x70, 0x48, 0x50, 0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84,
0x90, 0xD8, 0xAB, 0x00, 0... | (key: &[u8]) -> Vec<u8> {
let key_length = key.len();
let (rounds, sbox_round, extra_expansions) = match key_length {
16 => (10, false, 0),
24 => (12, false, 2),
32 => (14, true, 3),
len => panic!("Unsupported key length {}", len),
};
let expanded_key_size = 16 * (rounds + 1);
let mut expanded... | expand_key | identifier_name |
aes.rs | ] = [0, 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12, 1, 6, 11];
fn shift_rows(state: &mut [u8]) {
let copy = util::convert_to_fixed_array(state);
for (index, e) in state.iter_mut().enumerate() {
*e = copy[ROW_SHIFTS[index]];
}
}
#[test]
fn test_shift_rows() {
let mut rows = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,... | }
| random_line_split | |
tcp.rs | , relay::socks5::Address, ServerAddr};
use super::{
sys::{set_tcp_fastopen, TcpStream as SysTcpStream},
AcceptOpts,
ConnectOpts,
};
/// TcpStream for outbound connections
#[pin_project]
pub struct TcpStream(#[pin] SysTcpStream);
impl TcpStream {
/// Connects to address
pub async fn connect_with_o... | debug!(
"0.0.0.0:{} may have already been occupied, retry with IPV6_V6ONLY",
addr.port()
);
set_only_v6(&socket, true);
socket.bind(*addr)?;
}
Err(err) => retu... | // This is probably 0.0.0.0 with the same port has already been occupied | random_line_split |
tcp.rs | relay::socks5::Address, ServerAddr};
use super::{
sys::{set_tcp_fastopen, TcpStream as SysTcpStream},
AcceptOpts,
ConnectOpts,
};
/// TcpStream for outbound connections
#[pin_project]
pub struct TcpStream(#[pin] SysTcpStream);
impl TcpStream {
/// Connects to address
pub async fn connect_with_op... | (self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<io::Result<()>> {
self.project().0.poll_flush(cx)
}
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<io::Result<()>> {
self.project().0.poll_shutdown(cx)
}
}
/// `TcpListener` for accepting inbound connect... | poll_flush | identifier_name |
tcp.rs | }
};
Ok(TcpStream(stream))
}
}
impl Deref for TcpStream {
type Target = TokioTcpStream;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for TcpStream {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl AsyncRead for ... | self.0.as_raw_fd()
}
}
| identifier_body | |
signature.go | (Disclosure []byte) []int {
HiddenIndices := make([]int, 0)
for index, disclose := range Disclosure {
if disclose == 0 {
HiddenIndices = append(HiddenIndices, index)
}
}
return HiddenIndices
}
// NewSignature creates a new idemix signature (Schnorr-type signature)
// The []byte Disclosure steers which attri... | hiddenIndices | identifier_name | |
signature.go |
HiddenIndices := hiddenIndices(Disclosure)
// Start sig
r1 := RandModOrder(rng)
r2 := RandModOrder(rng)
r3 := FP256BN.NewBIGcopy(r1)
r3.Invmodp(GroupOrder)
Nonce := RandModOrder(rng)
A := EcpFromProto(cred.A)
B := EcpFromProto(cred.B)
APrime := FP256BN.G1mul(A, r1) // A' = A^{r1}
ABar := FP256BN.G1mul(B... | {
return nil, errors.Errorf("cannot create idemix signature: received nil input")
} | conditional_block | |
signature.go | (EcpFromProto(ipk.HAttrs[HiddenIndices[2*i]]).Mul2(rAttrs[2*i], EcpFromProto(ipk.HAttrs[HiddenIndices[2*i+1]]), rAttrs[2*i+1]))
}
if len(HiddenIndices)%2 != 0 {
t2.Add(FP256BN.G1mul(EcpFromProto(ipk.HAttrs[HiddenIndices[len(HiddenIndices)-1]]), rAttrs[len(HiddenIndices)-1]))
}
t3 := HSk.Mul2(rSk, HRand, rRNym)
... | {
HiddenIndices := hiddenIndices(Disclosure)
APrime := EcpFromProto(sig.GetAPrime())
ABar := EcpFromProto(sig.GetABar())
BPrime := EcpFromProto(sig.GetBPrime())
Nym := EcpFromProto(sig.GetNym())
ProofC := FP256BN.FromBytes(sig.GetProofC())
ProofSSk := FP256BN.FromBytes(sig.GetProofSSk())
ProofSE := FP256BN.Fro... | identifier_body | |
signature.go | 6BN.G1mul(APrime, FP256BN.FromBytes(cred.E))) // barA = A'^{-e} b^{r1}
BPrime := FP256BN.G1mul(B, r1)
HRand := EcpFromProto(ipk.HRand)
HSk := EcpFromProto(ipk.HSk)
BPrime.Sub(FP256BN.G1mul(HRand, r2)) // b' = b^{r1} h_r^{-r2}
S := FP256BN.FromBytes(cred.S)
E := FP256BN.FromBytes(cred.E)
sPrime := Modsub(S, FP... | Htp1 := H.Mul(temp1)
e2 := FP256BN.Ate(W,Htp1)
e2.Inverse()
e2.Mul(e1)
Htp2 := H.Mul(temp2)
e4 := FP256BN.Ate(GenG2,Htp2)
e4.Inverse()
e4.Mul(e2)
R3 := FP256BN.Fexp(e4)
R4 := FP256BN.G1mul(T1,rx)
R4.Sub(U.Mul(rDelta1))
R5 := FP256BN.G1mul(T2,rx)
R5.Sub(V.Mul(rDelta2))
// proofData is the data being hash... |
//compute pairing
Grx := GenG2.Mul(rx)
T4 := H.Mul(temp)
e1 := FP256BN.Ate2(Grx,Ax,Grx,T4) | random_line_split |
in-memory-plants-db-service.ts | () {
this.categories = [
{
'id': 0,
'name': 'Balkonnövények',
'plantsCount': 3
},
{
'id': 1,
'name': 'Rózsák',
'plantsCount': 4
},
{
'id': 2,
'name': 'Bogyós gyülömcsök',
'plantsCount': 5
},
{
'... | constructor | identifier_name | |
in-memory-plants-db-service.ts | 0 centiméteresre is megnövő fénylő virágok finom illatosak. Nem kell már az árnyékban sem nélkülöznie ' +
'a bőséges virágzást! Ilyen helyekre a begóniák ültetése a legjobb választás. Egészen őszig messziről fénylenek ' +
'virágai. Jó minőségű balkon virágföldet és rendszeres öntözést kíván.',
'... | 'description': 'Tűzpiros virágai fehéren csíkozottak. Mindehhez elragadó illat párosul.',
'plantingTime': ['MARCH', 'APRIL', 'MAY', 'OCT', 'NOV'],
'waterReq': 'MEDIUM',
'nutritionReq': 'BIWEEKLY',
'isFavorite': true,
'imageUrl': 'https://www.starkl.hu/img/eshop/thumbnails... | 'categoryId': 1,
'isFrostProof': true,
'lightReq': 'HALF_SHADY', | random_line_split |
in-memory-plants-db-service.ts | ', 'APRIL', 'MAY', 'SEPT', 'OCT', 'NOV'],
'waterReq': 'MEDIUM',
'nutritionReq': 'NONE',
'isFavorite': false,
'imageUrl': 'https://www.starkl.hu/img/eshop/thumbnails/154530_jpg_345266_406_488.jpg'
},
{
'name': 'Vörös áfonya',
'price': 1690,
'id': 10,
... | conditional_block | ||
piv.rs | pecialPublications/NIST.SP.800-78-4.pdf
// TODO(zmb3): support non-RSA keys, if needed.
if cmd.p1 != 0x07 {
return Err(invalid_data_error(&format!(
"unsupported algorithm identifier P1:{:#X} in general authenticate command",
cmd.p1
)));
}
... | {
vec![len as u8]
} | conditional_block | |
piv.rs | chunk = [0; CHUNK_SIZE];
let n = cursor.read(&mut chunk)?;
let mut chunk = chunk.to_vec();
chunk.truncate(n);
let remaining = cursor.get_ref().len() as u64 - cursor.position();
let status = if remaining == 0 {
Status::S... | {
let mut buf = Vec::new();
if let Some(data) = &self.data {
buf.extend_from_slice(data);
}
let status: [u8; 2] = self.status.into();
buf.extend_from_slice(&status);
buf
} | identifier_body | |
piv.rs | , _cmd: Command<S>) -> RdpResult<Response> {
// CHINK_SIZE is the max response data size in bytes, without resorting to "extended"
// messages.
const CHUNK_SIZE: usize = 256;
match &mut self.pending_response {
None => Ok(Response::new(Status::NotFound)),
Some(curs... | random_line_split | ||
piv.rs | (zmb3): compare algorithm against the private key using consts from
// https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-78-4.pdf
// TODO(zmb3): support non-RSA keys, if needed.
if cmd.p1 != 0x07 {
return Err(invalid_data_error(&format!(
"unsupported a... | len_to_vec | identifier_name | |
monitor.go | // create index indicates modification
m.ui.Output(fmt.Sprintf(
"Allocation %q modified: node %q, group %q",
limit(alloc.id, m.length), limit(alloc.node, m.length), alloc.group))
case alloc.desired == structs.AllocDesiredStatusRun:
// New allocation with desired status running
m.ui.Output(fmt.... | for cs, num := range metrics.ConstraintFiltered { | random_line_split | |
monitor.go | . This
// must be queried for explicitly so it is only included
// if there is important error information inside.
full *api.Allocation
}
// monitor wraps an evaluation monitor and holds metadata and
// state information.
type monitor struct {
ui cli.Ui
client *api.Client
state *evalState
// length determ... | }
// Check the allocations
for allocID, alloc := range update.allocs {
if existing, ok := existing.allocs[allocID]; !ok {
switch {
case alloc.index < update.index:
// New alloc with create index lower than the eval
// create index indicates modification
m.ui.Output(fmt.Sprintf(
"Allocation ... | {
m.Lock()
defer m.Unlock()
existing := m.state
// Swap in the new state at the end
defer func() {
m.state = update
}()
// Check if the evaluation was triggered by a node
if existing.node == "" && update.node != "" {
m.ui.Output(fmt.Sprintf("Evaluation triggered by node %q",
limit(update.node, m.lengt... | identifier_body |
monitor.go | This
// must be queried for explicitly so it is only included
// if there is important error information inside.
full *api.Allocation
}
// monitor wraps an evaluation monitor and holds metadata and
// state information.
type monitor struct {
ui cli.Ui
client *api.Client
state *evalState
// length determi... |
if len(evals) == 0 {
m.ui.Error(fmt.Sprintf("No evaluation(s) with prefix or id %q found", evalID))
return 1
}
if len(evals) > 1 {
// Format the evaluations
out := make([]string, len(evals)+1)
out[0] = "ID|Priority|Type|Triggered By|Status"
for i, eval := range evals {
out[i+1] = ... | {
m.ui.Error(fmt.Sprintf("Error reading evaluation: %s", err))
return 1
} | conditional_block |
monitor.go | ,
},
client: client,
state: newEvalState(),
length: length,
}
return mon
}
// update is used to update our monitor with new state. It can be
// called whether the passed information is new or not, and will
// only dump update messages when state changes.
func (m *monitor) update(update *evalState) {
m.Lock... | dumpAllocStatus | identifier_name | |
git.rs | self) -> Result<Option<Vec<u8>>> {
let partially_staged_files = self.get_partially_staged_files(true)?;
if partially_staged_files.is_empty() {
return Ok(None);
}
let mut diff_options = DiffOptions::new();
diff_options.show_binary(true);
for file in partially... | Stash | identifier_name | |
git.rs |
pub fn save_snapshot(&mut self, staged_files: Vec<PathBuf>) -> Result<Snapshot> {
let inner = || -> Result<Snapshot> {
let deleted_files = self.get_deleted_files()?;
let unstaged_diff = self.save_unstaged_diff()?;
let backup_stash = self.save_snapshot_stash()?;
... | {
// When strict hash verification is disabled, it means libgit2 will not
// compute the "object id" of Git objects (which is a SHA-1 hash) after
// reading them to verify they match the object ids being used to look
// them up. This improves performance, and I don't have in front of me
... | identifier_body | |
git.rs | backup stash with id {}.", stash_id))?;
self.repository.stash_apply(
stash_index,
Some(StashApplyOptions::default().reinstantiate_index()),
)?;
Ok(())
}
fn save_unstaged_diff(&self) -> Result<Option<Vec<u8>>> {
let partially_staged_files = self.get_par... | "Encountered error when deleting {}.",
file.as_ref().display()
)
})?;
} | random_line_split | |
client.rs | afka", "librdkafka: {} {}", fac, log_message),
RDKafkaLogLevel::Info => info!(target: "librdkafka", "librdkafka: {} {}", fac, log_message),
RDKafkaLogLevel::Debug => debug!(target: "librdkafka", "librdkafka: {} {}", fac, log_message),
}
}
/// Receives the statistics of the librd... | let mut group_list_ptr: *const RDKafkaGroupList = ptr::null_mut();
trace!("Starting group list fetch");
let ret = unsafe {
rdsys::rd_kafka_list_groups(
self.native_ptr(),
group_c_ptr,
&mut group_list_ptr as *mut *const RDKafkaGroupList,... | random_line_split | |
client.rs | unsafe {
rdsys::rd_kafka_destroy(self.ptr);
}
trace!("Client destroyed: {:?}", self.ptr);
}
}
/// A low level rdkafka client. This client shouldn't be used directly. The producer and consumer modules
/// provide different producer and consumer implementations based on top of `Cl... | {
let fac = CStr::from_ptr(fac).to_string_lossy();
let log_message = CStr::from_ptr(buf).to_string_lossy();
let context = Box::from_raw(rdsys::rd_kafka_opaque(client) as *mut C);
(*context).log(
RDKafkaLogLevel::from_int(level),
fac.trim(),
log_message.trim(),
);
mem::fo... | identifier_body | |
client.rs | afka", "librdkafka: {} {}", fac, log_message),
RDKafkaLogLevel::Info => info!(target: "librdkafka", "librdkafka: {} {}", fac, log_message),
RDKafkaLogLevel::Debug => debug!(target: "librdkafka", "librdkafka: {} {}", fac, log_message),
}
}
/// Receives the statistics of the librd... | <T: Into<Option<Duration>>>(
&self,
topic: &str,
partition: i32,
timeout: T,
) -> KafkaResult<(i64, i64)> {
let mut low = -1;
let mut high = -1;
let topic_c = CString::new(topic.to_string())?;
let ret = unsafe {
rdsys::rd_kafka_query_waterm... | fetch_watermarks | identifier_name |
three-d-bar-chart.component.ts | (private hostRef: ElementRef) { }
ngOnInit() {
if (this.data) {
this.createChart(this.data)
}
}
createChart(data) {
let el = this.chartContainer.nativeElement;
d3.select(el).select("svg").remove();
var margin = {
top: 30,
right: 20,
bottom: 40,
left: 20,
... | constructor | identifier_name | |
three-d-bar-chart.component.ts |
}
createChart(data) {
let el = this.chartContainer.nativeElement;
d3.select(el).select("svg").remove();
var margin = {
top: 30,
right: 20,
bottom: 40,
left: 20,
front: 0,
back: 0
},
width =
$(this.hostRef.nativeElement).parent().width() - margi... | {
this.createChart(this.data)
} | conditional_block | |
three-d-bar-chart.component.ts | 6);
var max = d3.max(data[0].map(function (d) {
return parseFloat(d.value);
}));
if (max < 100){
max = 100
}
if(max == undefined){
max = 100
}
var gridY = d3.scaleLinear().domain([0, max]).range(
[height, 0]);
var chart = d3.select(el).append("svg").attr("id",... | {
return d3.axisBottom(x)
.ticks(5)
} | identifier_body | |
three-d-bar-chart.component.ts | =
$(this.hostRef.nativeElement).parent().width() - margin.right - margin.left,
height = $(this.hostRef.nativeElement).parent().height() - margin.top - margin.bottom;
var depth = 100 - margin.front - margin.back;
var xScale = d3.scaleBand().range([0, width]).padding(0.5),
yScale = d3.scale... | .on("mouseover", function (d) {
if(d.value)
showPopover.call(this, d)
}).on("mouseout", function (d) {
removePopovers()
}) // sort based on distance from center, so we draw outermost
// bars first. otherwise, bars drawn later might overlap bars drawn first
.sort... | .style("cursor", "pointer") | random_line_split |
pageserver.rs | ").zip(get_arg("relish-storage-region"))
{
Some(RelishStorage::AwsS3 {
bucket_name,
bucket_region,
access_key_id: get_arg("relish-storage-access-key"),
secret_access_key: get_arg("relish-storage-secret-access-key"),
})
... | () -> Result<()> {
let arg_matches = App::new("Zenith page server")
.about("Materializes WAL stream to pages and serves them to the postgres")
.arg(
Arg::with_name("listen-pg")
.short("l")
.long("listen-pg")
.alias("listen") // keep some co... | main | identifier_name |
pageserver.rs | _config =
self.relish_storage
.as_ref()
.map(|storage_params| match storage_params.clone() {
RelishStorage::Local { local_path } => {
RelishStorageConfig::LocalFs(PathBuf::from(local_path))
}
... | {
info!("daemonizing...");
// There shouldn't be any logging to stdin/stdout. Redirect it to the main log so
// that we will see any accidental manual fprintf's or backtraces.
let stdout = log_file.try_clone().unwrap();
let stderr = log_file;
let daemonize = Daemonize::... | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.