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 |
|---|---|---|---|---|
fate_of_ashborne.py | #Ease of Use for True and False
T = True
F = False
towering_cliffs = txt.Location("The Towering Cliffs", -1, 0, 0, T, [T, T, F, F, F, F])
towering_cliffs.initial_description = "A few hundred feet below, a river rushes by and beats the side of the precipitous cliff. You look out in the distance and can see what lo... | """
| random_line_split | |
svm_1_0_0.py | values with the mean of each column...")
self.nan_replacer = Imputer()
self.nan_replacer.fit(X_raw)
X_raw = self.nan_replacer.transform(X_raw)
# Standardize input matrix to ease machine learning! Scaled data has zero mean and unit variance
print("Standardizing input matrix...")
... | s.classify(
svm_classifier,
s.X[test_index], | random_line_split | |
svm_1_0_0.py | for that spectrum
self.num_pep[peptide] += 1
for protein in proteins:
self.num_prot[protein].add(
(
line["Spectrum Title"],
uni_sequenc... | colnames.append("proteinId{0}".format(n_proteins + 1)) | conditional_block | |
svm_1_0_0.py | avages[2],
missed_cleavages[3],
missed_cleavages[4],
missed_cleavages[5],
enzN,
enzC,
mass,
pep_len,
num_pep,
num_prot,
pep_site,
is_shitty,
pep_charge_states,
num_... | msg = "Classifying {0} PSMs...".format(len(psm_matrix))
print(msg, end="\r")
for i, row in enumerate(psm_matrix):
# get the distance to the separating SVM hyperplane and use it as a score:
svm_score = classifier.decision_function(np.array([row]))[0]
features = tuple(... | identifier_body | |
svm_1_0_0.py | training examples can be "claimed".
"""
target_seqs = set()
decoy_seqs = set()
with open(self.csv_path, "r") as f:
reader = csv.DictReader(f)
sorted_reader = sorted(
reader,
reverse=self["bigger_scores_better"],
k... | (self, row):
"""
Converts a unified CSV row to a SVM feature matrix (numbers only!)
"""
sequence = unify_sequence(row["Sequence"])
charge = field_to_float(row["Charge"])
score = field_to_bayes_float(row[self.col_for_sorting])
calc_mz, exp_mz, calc_mass, exp_mass =... | row_to_features | identifier_name |
exec.rs | <DataFrame>, ExecutionError> {
let plan = LogicalPlan::CsvFile { filename: filename.to_string(), schema: schema.clone() };
Ok(Box::new(DF { ctx: Box::new((*self).clone()), plan: Box::new(plan) }))
}
pub fn register_table(&mut self, name: String, schema: Schema) {
self.schemas.insert(nam... |
ctx.define_function(&STPointFunc {});
let df = ctx.sql(&"SELECT ST_AsText(ST_Point(lat, lng)) FROM uk_cities").unwrap();
| random_line_split | |
exec.rs | |r| match r {
Ok(record) => self.create_tuple(&record),
Err(e) => Err(ExecutionError::CsvError(e))
});
Box::new(tuple_iter)
}
fn schema<'a>(&'a self) -> &'a Schema {
&self.schema
}
}
impl SimpleRelation for FilterRelation {
fn scan<'a>(&'a self, ctx: ... | select | identifier_name | |
exec.rs | _ctx: &'a ExecutionContext) -> Box<Iterator<Item=Result<Row,ExecutionError>> + 'a> {
let buf_reader = BufReader::new(&self.file);
let csv_reader = csv::Reader::from_reader(buf_reader);
let record_iter = csv_reader.into_records();
let tuple_iter = record_iter.map(move|r| match r {
... | {
//TODO: this is a huge hack since the functions have already been registered with the
// execution context ... I need to implement this so it dynamically loads the functions
match function_name.to_lowercase().as_ref() {
"sqrt" => Ok(Box::new(SqrtFunction {})),
"st_poi... | identifier_body | |
refresh.go | () *cobra.Command {
var debug bool
var expectNop bool
var message string
var execKind string
var execAgent string
var stackName string
// Flags for remote operations.
remoteArgs := RemoteArgs{}
// Flags for engine.UpdateOptions.
var jsonDisplay bool
var diffDisplay bool
var eventLogPath string
var parall... | newRefreshCmd | identifier_name | |
refresh.go | "false" && filestateBackend {
opts.Display.SuppressPermalink = true
}
s, err := requireStack(ctx, stackName, stackOfferNew, opts.Display)
if err != nil {
return result.FromError(err)
}
proj, root, err := readProject()
if err != nil {
return result.FromError(err)
}
m, err := getUp... | {
pending = append(pending, op)
continue
} | conditional_block | |
refresh.go | )
}
proj, root, err := readProject()
if err != nil {
return result.FromError(err)
}
m, err := getUpdateMetadata(message, root, execKind, execAgent, false, cmd.Flags())
if err != nil {
return result.FromError(fmt.Errorf("gathering environment metadata: %w", err))
}
cfg, sm, err := getS... | {
return totalStateEdit(ctx, s, yes, opts, func(opts display.Options, snap *deploy.Snapshot) error {
var pending []resource.Operation
for _, op := range snap.PendingOperations {
if op.Resource == nil {
return fmt.Errorf("found operation without resource")
}
if op.Type != resource.OperationTypeCreating... | identifier_body | |
refresh.go | "the program text isn't updated accordingly, subsequent updates may still appear to be out of\n" +
"synch with respect to the cloud provider's source of truth.\n" +
"\n" +
"The program to run is loaded from the project in the current directory. Use the `-C` or\n" +
"`--cwd` flag to use a different direct... | Short: "Refresh the resources in a stack",
Long: "Refresh the resources in a stack.\n" +
"\n" +
"This command compares the current stack's resource state with the state known to exist in\n" +
"the actual cloud provider. Any such changes are adopted into the current stack. Note that if\n" + | random_line_split | |
main.rs | , $y:expr, $w:expr, $h:expr) => (
Rect::new($x as i32, $y as i32, $w as u32, $h as u32)
)
);
trait PositionStrategy {
fn next_position(&mut self, rect: Rect, within_rect: Rect) -> Rect;
fn reset(&mut self) |
}
struct RandomPositionStrategy {}
impl PositionStrategy for RandomPositionStrategy {
// Return a random position that fits rect within rect
fn next_position(&mut self, rect: Rect, within_rect: Rect) -> Rect {
let rx: f64 = thread_rng().gen();
let ry: f64 = thread_rng().gen();
let pos... | {
} | identifier_body |
main.rs | , $y:expr, $w:expr, $h:expr) => (
Rect::new($x as i32, $y as i32, $w as u32, $h as u32)
)
);
trait PositionStrategy {
fn next_position(&mut self, rect: Rect, within_rect: Rect) -> Rect;
fn reset(&mut self) {
}
}
struct RandomPositionStrategy {}
impl PositionStrategy for RandomPositionStrateg... | .collect();
let mut background_color = random_colour(Color::RGB(255, 255, 255));
'running: loop {
for event in event_pump.poll_iter() {
match event {
Event::Quit { .. }
| Event::KeyDown {
keycode: Some(Keycode::Escape),
... | ("U", "upsiedaisy"),
("W", "woody"),
].iter()
.map(|(s1, s2)| (s1.to_string(), s2.to_string())) | random_line_split |
main.rs | , $y:expr, $w:expr, $h:expr) => (
Rect::new($x as i32, $y as i32, $w as u32, $h as u32)
)
);
trait PositionStrategy {
fn next_position(&mut self, rect: Rect, within_rect: Rect) -> Rect;
fn | (&mut self) {
}
}
struct RandomPositionStrategy {}
impl PositionStrategy for RandomPositionStrategy {
// Return a random position that fits rect within rect
fn next_position(&mut self, rect: Rect, within_rect: Rect) -> Rect {
let rx: f64 = thread_rng().gen();
let ry: f64 = thread_rng().ge... | reset | identifier_name |
main.rs | if self.next_y > within_rect.bottom() as u32 {
self.next_y = 0;
}
let y = self.next_y;
let x = self.next_x;
self.next_x = x + rect.width();
rect!(x, y, rect.width(), rect.height())
}
fn reset(&mut self) {
self.next_x = 0;
self.next_y... | {
let mut surface = load_image(&filename);
let sf = (100f64 / surface.height() as f64);
println!("{}", sf );
let surface = surface.rotozoom(0f64, sf, false).unwrap();
let texture = texture_creator
... | conditional_block | |
system.rs | >::put(&header.number);
<ParentHash>::put(&header.parent_hash);
<StorageDigest>::put(header.digest());
storage::unhashed::put(well_known_keys::EXTRINSIC_INDEX, &0u32);
// try to read something that depends on current header digest
// so that it'll be included in execution proof
if let Some(generic::DigestItem::O... | }
if let Some(new_authorities) = o_new_authorities {
digest.push(generic::DigestItem::Consensus(*b"aura", new_authorities.encode()));
digest.push(generic::DigestItem::Consensus(*b"babe", new_authorities.encode()));
}
if let Some(new_config) = new_changes_trie_config {
digest.push(generic::DigestItem::Change... | {
let extrinsic_index: u32 = storage::unhashed::take(well_known_keys::EXTRINSIC_INDEX).unwrap();
let txs: Vec<_> = (0..extrinsic_index).map(ExtrinsicData::take).collect();
let extrinsics_root = trie::blake2_256_ordered_root(txs).into();
let number = <Number>::take().expect("Number is set by `initialize_block`");
l... | identifier_body |
system.rs | >::put(&header.number);
<ParentHash>::put(&header.parent_hash);
<StorageDigest>::put(header.digest());
storage::unhashed::put(well_known_keys::EXTRINSIC_INDEX, &0u32);
// try to read something that depends on current header digest
// so that it'll be included in execution proof
if let Some(generic::DigestItem::O... | else {
vec![]
};
let provides = vec![encode(&tx.from, tx.nonce)];
Ok(ValidTransaction { priority: tx.amount, requires, provides, longevity: 64, propagate: true })
}
/// Execute a transaction outside of the block execution function.
/// This doesn't attempt to validate anything regarding the block.
pub fn execu... | {
vec![encode(&tx.from, tx.nonce - 1)]
} | conditional_block |
system.rs | >::put(&header.number);
<ParentHash>::put(&header.parent_hash);
<StorageDigest>::put(header.digest());
storage::unhashed::put(well_known_keys::EXTRINSIC_INDEX, &0u32);
// try to read something that depends on current header digest
// so that it'll be included in execution proof
if let Some(generic::DigestItem::O... | {
Verify,
Overwrite,
}
/// Actually execute all transitioning for `block`.
pub fn polish_block(block: &mut Block) {
execute_block_with_state_root_handler(block, Mode::Overwrite);
}
pub fn execute_block(mut block: Block) {
execute_block_with_state_root_handler(&mut block, Mode::Verify);
}
fn execute_block_with_s... | Mode | identifier_name |
system.rs | }
}
pub fn balance_of_key(who: AccountId) -> Vec<u8> {
who.to_keyed_vec(BALANCE_OF)
}
pub fn balance_of(who: AccountId) -> u64 {
storage::hashed::get_or(&blake2_256, &balance_of_key(who), 0)
}
pub fn nonce_of(who: AccountId) -> u64 {
storage::hashed::get_or(&blake2_256, &who.to_keyed_vec(NONCE_OF), 0)
}
pub fn ... | NewAuthorities get(fn new_authorities): Option<Vec<AuthorityId>>;
NewChangesTrieConfig get(fn new_changes_trie_config): Option<Option<ChangesTrieConfiguration>>;
StorageDigest get(fn storage_digest): Option<Digest>;
Authorities get(fn authorities) config(): Vec<AuthorityId>; | random_line_split | |
main.py | ():
cryptowatch_api.close()
transaction_api.close()
print("")
print("-" * 15)
print("closed Api connection")
database.commit()
database.close()
print("closed db connection")
print(time.ctime())
print("<---- QUITTING ---->")
"""
start cryptowatch
- make an api object
- make a db... | wrap_up | identifier_name | |
main.py | print("closed Api connection")
database.commit()
database.close()
print("closed db connection")
print(time.ctime())
print("<---- QUITTING ---->")
"""
start cryptowatch
- make an api object
- make a db object
- query api and insert into db in a loop
"""
stats_file_name = '/dev/shm/gdax.stats'
com... |
elif e.args[0] == 28 and error_stats[28] < 10:
pass # don't send an email on an occasional timeout
elif e.args[0] == 28 and error_stats[28] == 10:
cryptowatch_api.reset_connection()
transaction_api.reset_connection()
communicator.send_message("Timeout oc... | pass # wait for the network to get up maybe | conditional_block |
main.py | print("closed Api connection")
database.commit()
database.close()
print("closed db connection")
print(time.ctime())
print("<---- QUITTING ---->")
"""
start cryptowatch
- make an api object
- make a db object
- query api and insert into db in a loop
"""
stats_file_name = '/dev/shm/gdax.stats'
com... | error_stats[e.args[0]] = 1
else:
error_stats[e.args[0]] += 1
db_id = database.put_error(e, int(time.time()))
print(e)
print("error counts:", error_stats)
if e.args[0] == 7 and e.args[1].split()[4] in [
p["ip"] for h, p in PROXIES.items()
... | if e.args[0] not in error_stats.keys(): | random_line_split |
main.py |
"""
start cryptowatch
- make an api object
- make a db object
- query api and insert into db in a loop
"""
stats_file_name = '/dev/shm/gdax.stats'
communicator = comm.Comm('Trade_bot_test_run', 'email@example.com')
#leaving as example
#database = db.Bitmarket(DB_USER, DB_PASSWORD, dbname='bitmarket', dbhost='aruba... | cryptowatch_api.close()
transaction_api.close()
print("")
print("-" * 15)
print("closed Api connection")
database.commit()
database.close()
print("closed db connection")
print(time.ctime())
print("<---- QUITTING ---->") | identifier_body | |
delaunay_triangulation.rs | = 2 * n - 5;
Self {
triangles: Vec::with_capacity(max_triangles * 3),
halfedges: Vec::with_capacity(max_triangles * 3),
hull: Vec::new(),
}
}
/// The number of triangles in the triangulation.
pub fn len(&self) -> usize {
self.triangles.len() / 3
... | r.
pub fn triangle_center(&self, points: &[Point2D], triangle: usize) -> Point2D {
let p = self.points_of_triangle(triangle);
points[p[0]].circumcenter(&points[p[1]], &points[p[2]])
}
/// Returns the edges around a point connected to halfedge '*start*'.
pub fn edges_around_point(&self, ... | angle(t)
// .into_iter()
// .map(|e| self.triangles[*e])
// .collect()
let e = self.edges_of_triangle(triangle);
[
self.triangles[e[0]],
self.triangles[e[1]],
self.triangles[e[2]],
]
}
/// Triangle circumcente | identifier_body |
delaunay_triangulation.rs | = 2 * n - 5;
Self {
triangles: Vec::with_capacity(max_triangles * 3),
halfedges: Vec::with_capacity(max_triangles * 3),
hull: Vec::new(),
}
}
/// The number of triangles in the triangulation.
pub fn len(&self) -> usize {
self.triangles.len() / 3
... | result.push(incoming);
break;
}
// i += 1;
// if i > 100 {
// // println!("{} {} {}", outgoing, incoming, start);
// break;
// }
}
result
}
pub fn natural_neighbours_from_incoming_edge... | } else if incoming == start {
| conditional_block |
delaunay_triangulation.rs | }
impl Triangulation {
/// Constructs a new *Triangulation*.
fn new(n: usize) -> Self {
let max_triangles = 2 * n - 5;
Self {
triangles: Vec::with_capacity(max_triangles * 3),
halfedges: Vec::with_capacity(max_triangles * 3),
hull: Vec::new(),
}
}... | /// counter-clockwise.
pub hull: Vec<usize>, | random_line_split | |
delaunay_triangulation.rs | = 2 * n - 5;
Self {
triangles: Vec::with_capacity(max_triangles * 3),
halfedges: Vec::with_capacity(max_triangles * 3),
hull: Vec::new(),
}
}
/// The number of triangles in the triangulation.
pub fn len(&self) -> usize {
self.triangles.len() / 3
... | 0: usize,
i1: usize,
i2: usize,
a: usize,
b: usize,
c: usize,
) -> usize {
let t = self.triangles.len();
self.triangles.push(i0);
self.triangles.push(i1);
self.triangles.push(i2);
self.halfedges.push(a);
self.halfedges.push(b)... | f,
i | identifier_name |
api.py | ['no_check_certificate']
if settings['auth'] and not shortener: # do not leak PrivateBin authorization to shortener services
if settings['auth'] == 'basic' and settings['auth_user'] and settings['auth_pass']:
session.auth = (settings['auth_user'], settings['auth_pass'])
elif settings['a... | url = self.server + "?" + request,
headers = self.headers).json()
def delete(self, request):
# using try as workaround for versions < 1.3 due to we cant detect
# if server used version 1.2, where auto-deletion is added
try:
result = self.session.post(
... | def __init__(self, settings=None):
self.server = settings['server']
self.headers = {'X-Requested-With': 'JSONHttpRequest'}
self.session = _config_requests(settings, False)
def post(self, request):
result = self.session.post(
url = self.server,
headers = self... | identifier_body |
api.py | "https": settings['proxy']
})
else:
session.proxies.update({scheme: settings['proxy']})
return session
class PrivateBin:
def __init__(self, settings=None):
self.server = settings['server']
self.headers = {'X-Requested-With': 'JSONHttpRequest'}
self.se... | print("Short Link:\t{}".format(result.text)) | random_line_split | |
api.py | ['no_check_certificate']
if settings['auth'] and not shortener: # do not leak PrivateBin authorization to shortener services
if settings['auth'] == 'basic' and settings['auth_user'] and settings['auth_pass']:
session.auth = (settings['auth_user'], settings['auth_pass'])
elif settings['a... |
def getVersion(self):
result = self.session.get(
url = self.server + '?jsonld=paste',
headers = self.headers)
try:
jsonldSchema = result.json()
return jsonldSchema['@context']['v']['@value'] \
if ('@context' in jsonldSchema and
... | PBinCLIError("Something went wrong...\nError: Empty response.") | conditional_block |
api.py | ['no_check_certificate']
if settings['auth'] and not shortener: # do not leak PrivateBin authorization to shortener services
if settings['auth'] == 'basic' and settings['auth_user'] and settings['auth_pass']:
session.auth = (settings['auth_user'], settings['auth_pass'])
elif settings['a... | (self, url):
request = {'url': url}
try:
result = self.session.post(
url = "https://clck.ru/--",
data = request)
print("Short Link:\t{}".format(result.text))
except Exception as ex:
PBinCLIError("clck.ru: unexcepted behavior: {... | _clckru | identifier_name |
txn_process.go | WithError{Key: key, TxnOperation: kvs.PreProcess, Error: kvs.ErrUnregisteredValueType})
continue
}
value = reflect.New(valueType.Elem()).Interface().(proto.Message)
// try to deserialize the value
err := lazyValue.GetValue(value)
if err != nil {
errors = append(errors, kvs.KeyWithError{Key: key, ... | {
s.Log.WithFields(logging.Fields{
"txnSeqNum": txnSeqNum,
"key": key,
}).Warn("Transaction attempting to change a derived value")
return false
} | conditional_block | |
txn_process.go | 2. Simulation (skipped for SB notification): simulating transaction without
// actually executing any of the Add/Delete/Modify/Update operations in order
// to obtain the "execution plan"
// 3. Pre-recording: logging transaction arguments + plan before execution to
// persist some information in case there... | })
}
}
// postProcessTransaction schedules retry for failed operations and propagates
// errors to the subscribers and to the caller of a blocking commit.
func (s *Scheduler) postProcessTransaction(txn *preProcessedTxn, executed kvs.RecordedTxnOps, failed map[string]bool, preErrors []kvs.KeyWithError) {
// refre... | {
graphR := s.graph.Read()
defer graphR.Release()
for _, key := range qTxn.retry.keys.Iterate() {
node := graphR.GetNode(key)
if node == nil {
continue
}
lastChange := getNodeLastChange(node)
if lastChange.txnSeqNum > qTxn.retry.txnSeqNum {
// obsolete retry, the value has been changed since the fai... | identifier_body |
txn_process.go | origin: kvs.FromSB,
})
}
// preProcessNBTransaction unmarshalls transaction values and for resync also refreshes the graph.
func (s *Scheduler) preProcessNBTransaction(qTxn *queuedTxn, preTxn *preProcessedTxn) (errors []kvs.KeyWithError) {
// unmarshall all values
graphR := s.graph.Read()
for key, lazyValue := ... | validTxnValue | identifier_name | |
txn_process.go | Pre-recording
preTxnRecord := s.preRecordTransaction(txn, simulatedOps, preErrors)
// 5. Execution:
if eligibleForExec {
executedOps, failed = s.executeTransaction(txn, false)
}
stopTime = time.Now()
// 6. Recording:
s.recordTransaction(preTxnRecord, executedOps, startTime, stopTime)
// 7. Post-processing... | random_line_split | ||
model.py |
def get_classes(preds):
# Function to calculate the accuracy of our predictions vs labels
# Based on https://medium.com/@aniruddha.choudhury94/part-2-bert-fine-tuning-tutorial-with-pytorch-for-text-classification-on-the-corpus-of-linguistic-18057ce330e1
pred_flat = np.argmax(preds, axis=1).flatten()
... | '
Takes a time in seconds and returns a string hh:mm:ss
Based on https://medium.com/@aniruddha.choudhury94/part-2-bert-fine-tuning-tutorial-with-pytorch-for-text-classification-on-the-corpus-of-linguistic-18057ce330e1
'''
# Round to the nearest second.
elapsed_rounded = int(round((elapsed)))
... | identifier_body | |
model.py | _parameters())
no_decay = ['bias', 'gamma', 'beta']
optimizer_grouped_parameters = [
{'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)],
'weight_decay_rate': 0.01},
{'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)],
'we... | ews_clusters):
for news_index, clusters in news_clusters.items():
for lst in clusters:
lst.sort()
clusters.sort(key=lambda x: x[0])
def check_duplicates(news_clusters):
# Check an element exists in other lists
for news_index, clusters in news_clusters.items():
for lst in clusters:
... | rt_clusters(n | identifier_name |
model.py | :.3f}".format(eval_accuracy/nb_eval_steps))
return predictions, sent_logits
def sort_clusters(news_clusters):
for news_index, clusters in news_clusters.items():
for lst in clusters:
lst.sort()
clusters.sort(key=lambda x: x[0])
def check_duplicates(news_clusters):
# Check an element exists... | sentences.loc[sentences['Sentences'] == row['Sen_min'], 'Group'] = sentences.loc[sentences['Sentences'] == row['Sen_max'], 'Group'].iloc[0]
elif sentences.loc[sentences['Sentences'] == row['Sen_max'], 'Group'].iloc[0] == 0: | random_line_split | |
model.py | _parameters())
no_decay = ['bias', 'gamma', 'beta']
optimizer_grouped_parameters = [
{'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)],
'weight_decay_rate': 0.01},
{'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)],
'we... | # Unpack this training batch from our dataloader.
#
# As we unpack the batch, we'll also copy each tensor to the GPU using the
# `to` method.
#
# `batch` contains three pytorch tensors:
# [0]: input ids
# [1]: attenti... | apsed = format_time(time.time() - t0)
# Report progress.
print(' Batch {:>5,} of {:>5,}. Elapsed: {:}.'.format(step, len(train_dataloader), elapsed))
| conditional_block |
toggle.rs | {
ids: Ids,
}
widget_ids! {
struct Ids {
circles[],
rectangles[],
phantom_line,
}
}
#[derive(Copy, Clone, Debug, Default, PartialEq, WidgetStyle)]
pub struct Style {
#[conrod(default = "theme.shape_color")]
pub color: Option<conrod::Color>,
#[conrod(default = "4.0")]
... | State | identifier_name | |
toggle.rs | polate(bool),
/// Indicatees that the toggle value has changed since the last update.
SwitchTo(bool),
/// Some event which would mutate the envelope has occurred.
Mutate(super::Mutate<ToggleValue>),
}
impl<'a> Toggle<'a> {
/// Construct a new default Automation.
pub fn new(bars: &'a [time::Time... |
builder_methods! {
pub point_radius { style.point_radius = Some(conrod::Scalar) }
}
}
impl<'a> track::Widget for Toggle<'a> {
fn playhead(mut self, playhead: (Ticks, Ticks)) -> Self {
self.maybe_playhead = Some(playhead);
self
}
}
impl<'a> conrod::Colorable for Toggle<'a> {
... | {
Toggle {
bars: bars,
ppqn: ppqn,
maybe_playhead: None,
envelope: envelope,
common: widget::CommonBuilder::default(),
style: Style::default(),
}
} | identifier_body |
toggle.rs | able, Positionable};
let widget::UpdateArgs {
id,
rect,
state,
style,
ui,
..
} = args;
let Toggle {
envelope,
bars,
ppqn,
maybe_playhead,
..
} = self;
... | // // Only draw the clicked point if it is still before the first point.
// Clicked(Elem::BeforeFirstPoint, _, _) =>
// match envelope.points().nth(0) {
// Some(p) if ticks <= p.ticks => color.clicked().alpha(0.7), | random_line_split | |
ArabicOCR.py |
# i+=1
# words=[]
# word_k= len(cfile[img].keys())
# for word in range(word_k):
# word_1=[]
# for char in cfile[img][str(word)].keys():
# word_1+=[np.array(cfile[img][str(word)][char])]
# words+=[word_1]
# imgs+=[words]
#... | (string, str_list):
res = [ele for ele in str_list if(ele in string)]
return bool(res)
def readImages(folder, trainTest = 0):
images = []
folders = [f for f in glob.glob(folder + "**/*", recursive=True)]
y_vals = []
filesNames = []
for folder in folders:
img_files = [img_file for i... | contains | identifier_name |
ArabicOCR.py |
# i+=1
# words=[]
# word_k= len(cfile[img].keys())
# for word in range(word_k):
# word_1=[]
# for char in cfile[img][str(word)].keys():
# word_1+=[np.array(cfile[img][str(word)][char])]
# words+=[word_1]
# imgs+=[words]
#... | skippedImages = 0
TotalImages = 0
processes = []
start_time = timeit.default_timer()
dataset = sorted(glob.glob(TRAINING_DATASET + "*/*.png"), key=natural_keys)[4400:4600] # 3000 DONE
for i in list(dataset):
p = Process(target=loop, args=(i,))
p... | processedCharacters = 0
ignoredWords = 0
processedWords = 0
segmented = None
| random_line_split |
ArabicOCR.py | # i+=1
# words=[]
# word_k= len(cfile[img].keys())
# for word in range(word_k):
# word_1=[]
# for char in cfile[img][str(word)].keys():
# word_1+=[np.array(cfile[img][str(word)][char])]
# words+=[word_1]
# imgs+=[words]
# ... | print("running time = ", timeit.default_timer() - start_time)
print('Finished All#########################################')
elif mode==2:
featuresList=list(glob.glob("textFiles" + "/*.txt"))[: | in()
| conditional_block |
ArabicOCR.py |
# i+=1
# words=[]
# word_k= len(cfile[img].keys())
# for word in range(word_k):
# word_1=[]
# for char in cfile[img][str(word)].keys():
# word_1+=[np.array(cfile[img][str(word)][char])]
# words+=[word_1]
# imgs+=[words]
#... |
def loop(i):
pictureFeatures = []
pictureLabels = []
# actualCharacters = []
image = cv2.imread(i)
textFileName = i[:-4].replace('scanned', 'text')
textWords = open(textFileName + '.txt', encoding='utf-8').read().replace('\n', ' ').split(' ')
textWords = [item for item in textWords if i... | lines = LineSegmentation(img, saveResults=False)
# Segment lines into words
words = []
for i in range(len(lines)):
words.extend(WordSegmentation(lines[i], lineNumber = i, saveResults=False))
characters = []
# Segment words into characters
for word in words:
characters.append(Char... | identifier_body |
trace_service.pb.go | () { *m = StreamTracesMessage{} }
func (m *StreamTracesMessage) String() string { return proto.CompactTextString(m) }
func (*StreamTracesMessage) ProtoMessage() {}
func (*StreamTracesMessage) Descriptor() ([]byte, []int) {
return fileDescriptor_838555a39f11343b, []int{1}
}
func (m *StreamTracesMessage) XXX... | Reset | identifier_name | |
trace_service.pb.go | acesMessage{} }
func (m *StreamTracesMessage) String() string { return proto.CompactTextString(m) }
func (*StreamTracesMessage) ProtoMessage() {}
func (*StreamTracesMessage) Descriptor() ([]byte, []int) {
return fileDescriptor_838555a39f11343b, []int{1}
}
func (m *StreamTracesMessage) XXX_Unmarshal(b []byte) error... |
return nil
}
func init() {
proto.RegisterType((*StreamTracesResponse)(nil), "envoy.service.trace.v3alpha.StreamTracesResponse")
proto.RegisterType((*StreamTracesMessage)(nil), "envoy.service.trace.v3alpha.StreamTracesMessage")
proto.RegisterType((*StreamTracesMessage_Identifier)(nil), "envoy.service.trace.v3alpha... | {
return m.Node
} | conditional_block |
trace_service.pb.go |
func (m *StreamTracesResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_StreamTracesResponse.Merge(m, src)
}
func (m *StreamTracesResponse) XXX_Size() int {
return xxx_messageInfo_StreamTracesResponse.Size(m)
}
func (m *StreamTracesResponse) XXX_DiscardUnknown() {
xxx_messageInfo_StreamTracesResponse.DiscardU... | {
return xxx_messageInfo_StreamTracesResponse.Marshal(b, m, deterministic)
} | identifier_body | |
trace_service.pb.go | 0x93, 0xfb, 0xdd, 0xf6, 0x94,
0x68, 0x3a, 0xc3, 0x4c, 0x03, 0x4a, 0x51, 0x02, 0x89, 0x24, 0x65, 0xf2, 0xed, 0x11, 0x69, 0x54,
0x21, 0x2a, 0xf3, 0x6c, 0xbc, 0x6c, 0x52, 0x10, 0xf5, 0xed, 0x23, 0x97, 0xed, 0xa5, 0x30, 0x93,
0x11, 0x24, 0xe8, 0x15, 0x0f, 0xbb, 0xe8, 0xee, 0xf2, 0x9d, 0x71, 0x12, 0x23, 0x3c, 0xdd, 0x2e,... | random_line_split | ||
msMHE_stgen.py | 01, ('PO_ic', ()): 1+0.02},
(1, 6): {('A', ('p',)): 1+alpha, ('kA', ()): 1+alpha, ('T_ic', ()): 1-0.005, ('A', ('i',)): 1-alpha, ('MY_ic', ()): 1-0.01, ('PO_ic', ()): 1+0.02},
(1, 7): {('A', ('p',)): 1+alpha, ('kA', ()): 1+alpha, ('T_ic', ()): 1-0.005, ('A', ('i',)): 1+alpha, ('MY_ic', ()): 1-0.01, ... |
x_e = [c.nmpc_trajectory[i,'tf'] for i in range(1,iters)]
for var in poi[:-2]:
if var == 'MX':
for k in [0,1]:
y_e = [c.nmpc_trajectory[i,(var,(k,))] for i in range(1,iters)]
y = [c.monitor[i][var,(1,cp,k,1)] for i in range(1,iters+1) for cp in range(ncp+1)]
... | x.append(x[-cp-1]+c.pc_trajectory['tf',(i,cp)] if i > 1 else c.pc_trajectory['tf',(i,cp)]) | conditional_block |
msMHE_stgen.py | msMHEGen(d_mod = SemiBatchPolymerization_multistage,
d_mod_mhe = SemiBatchPolymerization,
y=y_vars,
x=x_vars,
x_noisy=x_noisy,
p_noisy=p_noisy,
u=u,
u_bounds = u_bounds,
tf_bounds = tf_bounds,
poi = x_vars,
... | random_line_split | ||
islandora_bulk_downloader.py |
def get_rels_ext_properties(pid):
rels_ext_properties = dict()
url = args.host.rstrip('/') + '/islandora/object/' + pid + '/datastream/RELS-EXT/view'
request_url = urllib.request.urlopen(url)
rels_ext_xml = request_url.read().decode('utf-8').strip()
rels_ext_properties['PID'] = pid
# <fedora:... | return pid.replace(':', '__') | identifier_body | |
islandora_bulk_downloader.py | # <fedora:isMemberOfCollection rdf:resource="info:fedora/km:collection"/>
isMemberOfCollections = re.findall('fedora:isMemberOfCollection rdf:resource="info:fedora/.*"', rels_ext_xml)
if len(isMemberOfCollections) > 0:
isMemberOfCollection = isMemberOfCollections[0].replace('fedora:isMemberOfCollection... | isSequenceNumberOfs = re.findall('>.*<', isSequenceNumberOf)
isSequenceNumberOf = isSequenceNumberOfs[0].lstrip('>')
isSequenceNumberOf = isSequenceNumberOf.rstrip('<')
rels_ext_properties['isSequenceNumberOf'] = isSequenceNumberOf
else:
rels_ext_properties['isSequenceNumberO... | isSequenceNumberOfs = re.findall('<islandora:isSequenceNumberOf.*>.*<', rels_ext_xml)
if len(isSequenceNumberOfs) > 0:
# Assumes that the object has only one parent.
isSequenceNumberOf = isSequenceNumberOfs[0].replace('<.*', '') | random_line_split |
islandora_bulk_downloader.py | (pid):
# Converts PID into a string suitable for use in filesystem paths.
# Uses __ in case some PIDs contain a single _.
return pid.replace(':', '__')
def get_rels_ext_properties(pid):
rels_ext_properties = dict()
url = args.host.rstrip('/') + '/islandora/object/' + pid + '/datastream/RELS-EXT/vie... | pid_to_path | identifier_name | |
islandora_bulk_downloader.py | # <fedora:isMemberOfCollection rdf:resource="info:fedora/km:collection"/>
isMemberOfCollections = re.findall('fedora:isMemberOfCollection rdf:resource="info:fedora/.*"', rels_ext_xml)
if len(isMemberOfCollections) > 0:
|
else:
rels_ext_properties['isMemberOfCollection'] = None
# Newspaper issues use isMemberOf in relationship to their newspaper and isSequenceNumber to sequence within that newspaper.
# <fedora:isMemberOf rdf:resource="info:fedora/ctimes:1"/>
# <islandora:isSequenceNumber>16219</islandora:isSequ... | isMemberOfCollection = isMemberOfCollections[0].replace('fedora:isMemberOfCollection rdf:resource="info:fedora/', '')
isMemberOfCollection = isMemberOfCollection.strip('"')
rels_ext_properties['isMemberOfCollection'] = isMemberOfCollection | conditional_block |
route_planner.rs | )
#[derive(Debug)]
pub struct Link {
/// Destination node for this link
pub to: NodeId,
/// Description of this link
pub desc: LinkDescription,
}
/// Table of all nodes (and links between them) known to an instance
struct NodeTable {
root_node: NodeId,
nodes: BTreeMap<NodeId, Node>,
version... |
}
Ok::<_, Error>(())
},
async move {
while let Some(status) = local_updates.next().await {
let mut node_table = local_node_table.lock().await;
let root_node = node_table.root_node;
if let Err(e) = node_table.update_link... | {
log::warn!("Update remote links from {:?} failed: {:?}", from_node_id, e);
continue;
} | conditional_block |
route_planner.rs | out)
#[derive(Debug)]
pub struct Link {
/// Destination node for this link
pub to: NodeId,
/// Description of this link
pub desc: LinkDescription,
}
/// Table of all nodes (and links between them) known to an instance
struct NodeTable {
root_node: NodeId,
nodes: BTreeMap<NodeId, Node>,
ver... | async move {
while let Some(status) = local_updates.next().await {
let mut node_table = local_node_table.lock().await;
let root_node = node_table.root_node;
if let Err(e) = node_table.update_links(root_node, status) {
log::warn!("Up... | }
Ok::<_, Error>(())
}, | random_line_split |
route_planner.rs | )
#[derive(Debug)]
pub struct Link {
/// Destination node for this link
pub to: NodeId,
/// Description of this link
pub desc: LinkDescription,
}
/// Table of all nodes (and links between them) known to an instance
struct NodeTable {
root_node: NodeId,
nodes: BTreeMap<NodeId, Node>,
version... |
fn update_links(&mut self, from: NodeId, links: Vec<LinkStatus>) -> Result<(), Error> {
self.get_or_create_node_mut(from).links.clear();
for LinkStatus { to, local_id, round_trip_time } in links.into_iter() {
self.update_link(from, to, local_id, LinkDescription { round_trip_time })?;
... | {
log::trace!(
"{:?} update_link: from:{:?} to:{:?} link_id:{:?} desc:{:?}",
self.root_node,
from,
to,
link_id,
desc
);
if from == to {
bail!("Circular link seen");
}
self.get_or_create_node_mut(t... | identifier_body |
route_planner.rs | out)
#[derive(Debug)]
pub struct Link {
/// Destination node for this link
pub to: NodeId,
/// Description of this link
pub desc: LinkDescription,
}
/// Table of all nodes (and links between them) known to an instance
struct NodeTable {
root_node: NodeId,
nodes: BTreeMap<NodeId, Node>,
ver... | (
&mut self,
from: NodeId,
to: NodeId,
link_id: NodeLinkId,
desc: LinkDescription,
) -> Result<(), Error> {
log::trace!(
"{:?} update_link: from:{:?} to:{:?} link_id:{:?} desc:{:?}",
self.root_node,
from,
to,
... | update_link | identifier_name |
flappy_bird.js | 2},
{sX: 276, sY: 139},
{sX: 276, sY: 164},
{sX: 276, sY: 139}
],
x: 70,
y: 120,
w: 34,
h: 26,
frame: 0,
rotation: 0,
gravity: 0.2,
speed: 0,
flight: 5,
radius: 12,
fly() {
this.speed = -this.flight;
},
update() {
let birdImg = this.animation[this.frame];
// bird c... | loop | identifier_name | |
flappy_bird.js | changeGameState(e) {
e.preventDefault();
if (e.type === 'touchstart') {
switch (gameState.current) {
case gameState.getReady:
gameState.current = gameState.playing;
break;
case gameState.playing:
bird.fly();
break;
case gameState.gameOver:
// if the cl... | this.rotation = toRadian(-20);
}
}
},
draw() {
let birdImg = this.animation[this.frame];
// rotate the bird
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.rotation);
// coordinates center in bird image rather than up-left corner
ctx.drawImage(sprite, birdI... | random_line_split | |
flappy_bird.js | GameState(e) {
e.preventDefault();
if (e.type === 'touchstart') {
switch (gameState.current) {
case gameState.getReady:
gameState.current = gameState.playing;
break;
case gameState.playing:
bird.fly();
break;
case gameState.gameOver:
// if the click is ... |
}
// draw game over Image
const gameOver = {
sX: | {
if (gameState.current === gameState.getReady) {
ctx.drawImage(sprite, this.sX, this.sY, this.w, this.h, this.x, this.y, this.w, this.h);
}
} | identifier_body |
lib.rs | #[no_mangle]
// This function returns the offset of the allocated buffer in wasm memory
pub fn alloc(size: u32) -> *mut u8 {
let mut buffer: Vec<u8> = Vec::with_capacity(size as usize);
let buffer_ptr = buffer.as_mut_ptr();
mem::forget(buffer);
buffer_ptr
}
#[no_mangle]
pub fn free(buffer_ptr: *mut u8,... |
});
}
#[cfg(test)]
mod kernel_test {
use super::*;
static POINT_DRAW_TIMES: Lazy<Mutex<u32>> = Lazy::new(|| Mutex::new(0));
// Override the extern functions
#[no_mangle]
extern "C" fn draw_point(_: u32, _: u32, _: f32) {
*POINT_DRAW_TIMES.lock().unwrap() += 1;
}
use std:... | {
// floor
let x = x as u32;
let y = y as u32;
let label_ratio = label as f32 / num_classes;
unsafe {
draw_point(x, y, label_ratio);
}
} | conditional_block |
lib.rs | #[no_mangle]
// This function returns the offset of the allocated buffer in wasm memory
pub fn alloc(size: u32) -> *mut u8 {
let mut buffer: Vec<u8> = Vec::with_capacity(size as usize);
let buffer_ptr = buffer.as_mut_ptr();
mem::forget(buffer);
buffer_ptr
}
#[no_mangle]
pub fn free(buffer_ptr: *mut u8,... |
const DATA_GEN_RADIUS: f32 = 1f32;
const SPIN_SPAN: f32 = PI;
const NUM_CLASSES: u32 = 3;
const DATA_NUM: u32 = 300;
const FC_SIZE: u32 = 100;
const REGULAR_RATE: f32 = 0.001f32;
const DESCENT_RATE: f32 = 1f32;
const DATA_GEN_RAND_MAX: f32 = 0.25f32;
const NETWORK_GEN_RAND_MAX: f32 ... | *POINT_DRAW_TIMES.lock().unwrap() += 1;
}
use std::f32::consts::PI; // for math functions | random_line_split |
lib.rs | let mut buffer: Vec<u8> = Vec::with_capacity(size as usize);
let buffer_ptr = buffer.as_mut_ptr();
mem::forget(buffer);
buffer_ptr
}
#[no_mangle]
pub fn free(buffer_ptr: *mut u8, size: u32) {
let _ = unsafe { Vec::from_raw_parts(buffer_ptr, 0, size as usize) };
}
#[no_mangle]
pub fn init(
data_ra... | {
init(
DATA_GEN_RADIUS,
SPIN_SPAN,
DATA_NUM,
NUM_CLASSES,
DATA_GEN_RAND_MAX,
NETWORK_GEN_RAND_MAX,
FC_SIZE,
DESCENT_RATE,
REGULAR_RATE,
);
let loss_before: f32 = train();
for _ in... | identifier_body | |
lib.rs | {
fc_size: u32,
num_classes: u32,
descent_rate: f32,
regular_rate: f32,
}
#[derive(Default)]
struct CriticalSection(MetaData, Data, Network);
// Imported js functions
extern "C" {
// for debug
fn log_u64(num: u32);
// for data pointer draw
// x,y: the offset from upper left corner
... | MetaData | identifier_name | |
common.js | --发布一条新评论(2018-04-09)
GiveTeaAMark: `${host}/LittleProgram/Review/GiveTeaAMark`,
//学生--删除评论(2018-04-09)
DeleteReview: `${host}/LittleProgram/Review/DeleteReview`,
//外教--获取某课程拼团成功信息列表(2018-04-09)
GetMyCorOrderList: `${host}/LittleProgram/OpenGrpOrder/GetMyCorOrderList`,
//外教-拼团详情
GetTeaOrderInfoList: `${ho... | f (callback) === 'function' ? callback : function (res) { };
wx.setStorageSync('userInfo', userInfo);
wx.request({
url: config.UpdateAvaUrlNick,
data: {
openId: wx.getStorageSync('openid'),
avaUrl: userInfo.avatarUrl,
nickName: userInfo.nickName,
gender: userInfo.gend... | identifier_body | |
common.js | 4-09)
ReleaseMyLearnNeed: `${host}/LittleProgram/LearnNeeds/ReleaseMyLearnNeed`,
//学生-我的-获取某需求信息以供修改(2018-04-09)
GetMyLearnNeedInfo: `${host}/LittleProgram/LearnNeeds/GetMyLearnNeedInfo`,
//学生--我的--修改需求(2018-04-09)
AlterMyLearnNeedInfo: `${host}/LittleProgram/LearnNeeds/AlterMyLearnNeedInfo`,
//学生--我的评论,评论列... | //保存用户类型
let userType = res.data.userType && res.data.userType; | random_line_split | |
common.js | MemRecord: `${host}/LittleProgram/ChatRecord/GetChatMemRecord`,
// 获取两人聊天记录(2018-04-12)
GetChatRecord: `${host}/LittleProgram/ChatRecord/GetChatRecord`,
// 获取聊天双方头像(2018-04-12)
GetUserInfo: `${host}/LittleProgram/UserInfo/GetUserInfo`,
// 外教-获取某外教所有课程所占用的时间段列表(2018-04-17)
GetAllTeaTimeTableInfo: `${host}/Li... | conditional_block | ||
common.js | MemRecord: `${host}/LittleProgram/ChatRecord/GetChatMemRecord`,
// 获取两人聊天记录(2018-04-12)
GetChatRecord: `${host}/LittleProgram/ChatRecord/GetChatRecord`,
// 获取聊天双方头像(2018-04-12)
GetUserInfo: `${host}/LittleProgram/UserInfo/GetUserInfo`,
// 外教-获取某外教所有课程所占用的时间段列表(2018-04-17)
GetAllTeaTimeTableInfo: `${host}/Li... | identifier_name | ||
cache.rs | }
}
}
_ => false
};
// Once we've recursively found all the generics, hoard off all the
// implementations elsewhere.
let ret = self.fold_item_recur(item).and_then(|item| {
if let clean::Item { inner: clean::ImplIte... | {
match *clean_type {
clean::ResolvedPath { ref path, .. } => {
let segments = &path.segments;
let path_segment = segments.into_iter().last().unwrap_or_else(|| panic!(
"get_index_type_name(clean_type: {:?}, accept_generic: {:?}) had length zero path",
... | identifier_body | |
cache.rs | are being indexed. Caches such methods
// and their parent id here and indexes them at the end of crate parsing.
orphan_impl_items: Vec<(DefId, clean::Item)>,
// Similarly to `orphan_impl_items`, sometimes trait impls are picked up
// even though the trait itself is not exported. This can happen if a ... | cache.external_paths.insert(did, (vec![e.name.to_string()], ItemType::Module));
}
// Cache where all known primitives have their documentation located.
//
// Favor linking to as local extern as possible, so iterate all crates in
// reverse topological order.
... | let extern_url = extern_html_root_urls.get(&e.name).map(|u| &**u);
cache.extern_locations.insert(n, (e.name.clone(), src_root,
extern_location(e, extern_url, &dst)));
let did = DefId { krate: n, index: CRATE_DEF_INDEX }; | random_line_split |
cache.rs | .paths.get(&did) {
// The current stack not necessarily has correlation
// for where the type was defined. On the other
// hand, `paths` always has the right
// information if present.
... | build_index | identifier_name | |
cache.rs | None, None), false)
} else {
let last = self.parent_stack.last().unwrap();
let did = *last;
let path = match self.paths.get(&did) {
// The current stack not necessarily has correlation
... | {
url.push('/')
} | conditional_block | |
l2fib_evpn_ipmac_info.pb.go |
var xxx_messageInfo_L2FibEvpnIpmacInfo_KEYS proto.InternalMessageInfo
func (m *L2FibEvpnIpmacInfo_KEYS) GetNodeId() string {
if m != nil {
return m.NodeId
}
return ""
}
func (m *L2FibEvpnIpmacInfo_KEYS) GetBdid() uint32 {
if m != nil {
return m.Bdid
}
return 0
}
func (m *L2FibEvpnIpmacInfo_KEYS) GetIpAdd... | {
xxx_messageInfo_L2FibEvpnIpmacInfo_KEYS.DiscardUnknown(m)
} | identifier_body | |
l2fib_evpn_ipmac_info.pb.go | *L2FibEvpnIpmacInfo_KEYS) GetBdid() uint32 {
if m != nil {
return m.Bdid
}
return 0
}
func (m *L2FibEvpnIpmacInfo_KEYS) GetIpAddress() string {
if m != nil {
return m.IpAddress
}
return ""
}
func (m *L2FibEvpnIpmacInfo_KEYS) GetIsLocal() bool {
if m != nil {
return m.IsLocal
}
return false
}
func (m ... | return false
}
func (m *L2FibEvpnIpmacInfo) GetArpNdProbePending() bool {
if m != nil {
return m.ArpNdProbePending
}
return false
}
func (m *L2FibEvpnIpmacInfo) GetArpNdDeletePending() bool {
if m != nil {
return m.ArpNdDeletePending
}
return false
}
func (m *L2FibEvpnIpmacInfo) GetIsLocalXr() bool {
if ... | if m != nil {
return m.ArpNdSyncPending
} | random_line_split |
l2fib_evpn_ipmac_info.pb.go | L2FibEvpnIpmacInfo_KEYS) GetBdid() uint32 {
if m != nil {
return m.Bdid
}
return 0
}
func (m *L2FibEvpnIpmacInfo_KEYS) GetIpAddress() string {
if m != nil |
return ""
}
func (m *L2FibEvpnIpmacInfo_KEYS) GetIsLocal() bool {
if m != nil {
return m.IsLocal
}
return false
}
func (m *L2FibEvpnIpmacInfo_KEYS) GetMacAddress() string {
if m != nil {
return m.MacAddress
}
return ""
}
type L2FibIpAddrT struct {
AddrType string `protobuf:"bytes,1,opt,nam... | {
return m.IpAddress
} | conditional_block |
l2fib_evpn_ipmac_info.pb.go | (src proto.Message) {
xxx_messageInfo_L2FibEvpnIpmacInfo_KEYS.Merge(m, src)
}
func (m *L2FibEvpnIpmacInfo_KEYS) XXX_Size() int {
return xxx_messageInfo_L2FibEvpnIpmacInfo_KEYS.Size(m)
}
func (m *L2FibEvpnIpmacInfo_KEYS) XXX_DiscardUnknown() {
xxx_messageInfo_L2FibEvpnIpmacInfo_KEYS.DiscardUnknown(m)
}
var xxx_messa... | XXX_Merge | identifier_name | |
constants.rs | Some("white".to_string()),
graph_color: Some("black".to_string()),
disabled_text_color: Some("gray".to_string()),
..ConfigColours::default()
};
pub static ref GRUVBOX_COLOUR_PALETTE: ConfigColours = ConfigColours {
table_header_color: Some("#ebdbb2".to_string()),
all_cpu... | // rx_color: None,
// tx_color: None,
// rx_total_color: None,
// tx_total_color: None,
// border_color: None,
// highlighted_border_color: None,
// text_color: None,
// selected_text_color: None,
// selected_bg_color: None,
// widget_title... | // all_cpu_color: None,
// avg_cpu_color: None,
// cpu_core_colors: None,
// ram_color: None,
// swap_color: None, | random_line_split |
etcd.go | Created uint64 `json:"createdIndex"`
Modified uint64 `json:"modifiedIndex"`
Key string `json:"key"`
Value string `json:"value"`
}
/**
* An etcd response
*/
type etcdResponse struct {
Action string `json:"action"`
Node ... |
/**
* Obtain the response
*/
func (e *etcdCacheEntry) Response() *etcdResponse {
e.RLock()
defer e.RUnlock()
return e.response
}
/**
* Set the response
*/
func (e *etcdCacheEntry) SetResponse(rsp *etcdResponse) {
e.Lock()
defer e.Unlock()
e.response = rsp
}
/**
* Add an observer for this entry and ... | {
return &etcdCacheEntry{key: key, response:rsp, observers: make([]etcdObserver, 0)}
} | identifier_body |
etcd.go | Created uint64 `json:"createdIndex"`
Modified uint64 `json:"modifiedIndex"`
Key string `json:"key"`
Value string `json:"value"`
}
/**
* An etcd response
*/
type etcdResponse struct {
Action string `json:"action"`
Node ... | () {
e.Lock()
defer e.Unlock()
e.observers = make([]etcdObserver, 0)
}
/**
* Are we watching this entry
*/
func (e *etcdCacheEntry) IsWatching() bool {
e.RLock()
defer e.RUnlock()
return e.watching
}
/**
* Start watching this entry for updates if we aren't already
*/
func (e *etcdCacheEntry) Watch(c *... | RemoveAllObservers | identifier_name |
etcd.go | Created uint64 `json:"createdIndex"`
Modified uint64 `json:"modifiedIndex"`
Key string `json:"key"`
Value string `json:"value"`
}
/**
* An etcd response
*/
type etcdResponse struct {
Action string `json:"action"`
Node ... |
e.RLock()
key := e.key
rsp := e.response
e.RUnlock()
rsp, err = c.get(key, true, rsp)
if err == io.EOF || err == io.ErrUnexpectedEOF {
errcount = 0
continue
}else if err != nil {
errcount++
delay := backoff * time.Duration(errcount * errcount)
if delay... | random_line_split | |
etcd.go | utex
config *EtcdConfig
props map[string]*etcdCacheEntry
}
/**
* Create a cache
*/
func newEtcdCache(config *EtcdConfig) *etcdCache {
return &etcdCache{config: config, props: make(map[string]*etcdCacheEntry)}
}
/**
* Obtain a response from the cache
*/
func (c *etcdCache) Get(key string) (*etcdRe... | {
if i > 0 { path += "/" }
path += url.QueryEscape(p)
} | conditional_block | |
shell.rs |
/// Gets the initial state injected by the server, if there was any. This is used to differentiate initial loads from subsequent ones,
/// which have different log chains to prevent double-trips (a common SPA problem).
pub fn get_initial_state() -> InitialState {
let val_opt = web_sys::window().unwrap().get("__PE... | {
let val_opt = web_sys::window().unwrap().get("__PERSEUS_RENDER_CFG");
let js_obj = match val_opt {
Some(js_obj) => js_obj,
None => return None,
};
// The object should only actually contain the string value that was injected
let cfg_str = match js_obj.as_string() {
Some(cfg... | identifier_body | |
shell.rs | js_obj = match val_opt {
Some(js_obj) => js_obj,
None => return None,
};
// The object should only actually contain the string value that was injected
let cfg_str = match js_obj.as_string() {
Some(cfg_str) => cfg_str,
None => return None,
};
let render_cfg = match se... | () -> InitialState {
let val_opt = web_sys::window().unwrap().get("__PERSEUS_INITIAL_STATE");
let js_obj = match val_opt {
Some(js_obj) => js_obj,
None => return InitialState::NotPresent,
};
// The object should only actually contain the string value that was injected
let state_str =... | get_initial_state | identifier_name |
shell.rs | js_obj = match val_opt {
Some(js_obj) => js_obj,
None => return None,
};
// The object should only actually contain the string value that was injected
let cfg_str = match js_obj.as_string() {
Some(cfg_str) => cfg_str,
None => return None,
};
let render_cfg = match se... | /// A representation of whether or not the initial state was present. If it was, it could be `None` (some templates take no state), and
/// if not, then this isn't an initial load, and we need to request the page from the server. It could also be an error that the server
/// has rendered.
pub enum InitialState {
//... | random_line_split | |
groups-edit.component.ts | this.route.paramMap.subscribe(map => {
this.group_id = map.get('parking_group_id');
});
this.route.queryParamMap.subscribe(map => {
this.fromPath = map.get('from') === 'detail' ? 'detail' : 'list';
});
this.searchParams.page_num = 1;
this.searchParams.page_size = GlobalConst.PageSize... | identifier_name | ||
groups-edit.component.ts | selector: 'app-groups-edit',
templateUrl: './groups-edit.component.html',
styleUrls: ['..//groups.component.css', './groups-edit.component.css'], | })
export class GroupsEditComponent implements OnInit, CanDeactivateComponent {
public groupsInfo: GroupEntity = new GroupEntity();
public updateGroupInfo: GroupEditEntity = new GroupEditEntity();
public groupTypeList: Array<number> = [1, 2, 3, 4, 5, 0];
public regionsList: Array<RegionEntity> = [];
publ... | providers: [ParkingsHttpService] | random_line_split |
groups-edit.component.ts | this.route.paramMap.subscribe(map => {
this.group_id = map.get('parking_group_id');
});
this.route.queryParamMap.subscribe(map => {
this.fromPath = map.get('from') === 'detail' ? 'detail' : 'list';
});
this.searchParams.page_num = 1;
this.searchParams.page_size = GlobalConst.PageSize... | identifier_body | ||
groups-edit.component.ts | editGroupsForm') public editGroupsForm: any;
/**
* 获取是否有组类型被选中了(表单校验)
* @returns {boolean}
*/
public get checkedGroupsType(): boolean {
if (this.temSelectedGroupArr.length > 0) {
return true;
}
return false;
}
constructor(private router: Router, private route: ActivatedRoute, privat... | .parkingsList.push(new ParkingItem(parking));
| conditional_block | |
review.go | ) {
if err := repo.VerifyCommit(revision); err != nil {
return nil, fmt.Errorf("Could not find a commit named %q", revision)
}
requestNotes := repo.GetNotes(requestRef, revision)
commentNotes := repo.GetNotes(commentRef, revision)
summary, err := getSummaryFromNotes(repo, revision, requestNotes, commentNotes)
i... | {
return false
} | conditional_block | |
review.go | func (thread *CommentThread) updateResolvedStatus() |
// Verify verifies the signature on a comment.
func (thread *CommentThread) Verify() error {
err := gpg.Verify(&thread.Comment)
if err != nil {
hash, _ := thread.Comment.Hash()
return fmt.Errorf("verification of comment [%s] failed: %s", hash, err)
}
for _, child := range thread.Children {
err = child.Verif... | {
resolved := updateThreadsStatus(thread.Children)
if resolved == nil {
thread.Resolved = thread.Comment.Resolved
return
}
if !*resolved {
thread.Resolved = resolved
return
}
if thread.Comment.Resolved == nil || !*thread.Comment.Resolved {
thread.Resolved = nil
return
}
thread.Resolved = resolved... | identifier_body |
review.go | func (thread *CommentThread) updateResolvedStatus() {
resolved := updateThreadsStatus(thread.Children)
if resolved == nil {
thread.Resolved = thread.Comment.Resolved
return
} | return
}
if thread.Comment.Resolved == nil || !*thread.Comment.Resolved {
thread.Resolved = nil
return
}
thread.Resolved = resolved
}
// Verify verifies the signature on a comment.
func (thread *CommentThread) Verify() error {
err := gpg.Verify(&thread.Comment)
if err != nil {
hash, _ := thread.Comment... |
if !*resolved {
thread.Resolved = resolved | random_line_split |
review.go | )
reviewSummary.Comments = comments
reviewSummary.Resolved = resolved
return &reviewSummary, nil
}
func GetComments(repo repository.Repo, revision string) ([]CommentThread, error) {
commentNotes := repo.GetNotes(comment.Ref, revision)
c, _ := getCommentsFromNotes(repo, revision, commentNotes)
return c, nil
}
//... | findLastCommit | identifier_name | |
lib.rs | static str>,
$(
pub $access: ComponentPresence<$ty>,
)+
}
impl $data {
pub fn new_empty() -> $data {
$data {
components: Vec::new(),
families: Vec::new(),
$(
... | (&mut self, ent: Entity) {
self.clear_family_data_for(ent);
self.components.remove(&ent);
}
fn remove_from_family(&mut self, family: &str, ent: Entity) {
let mut idx: Option<usize> = None;
{
let vec = self.families.get_mut(family).expect("No such family");
... | delete_component_data_for | identifier_name |
lib.rs | ` field of the `EntityManager`
pub trait EntityDataHolder {
fn new() -> Self;
/// Takes a map of all the defined families,
/// and returns the families that match this entity.
fn match_families(&self, &FamilyMap) -> Vec<&'static str>;
/// Sets the families this entity belongs to to `families`
... | {
self.processor.add_processable(self.ent);
} | conditional_block | |
lib.rs | 'static str>,
$(
pub $access: ComponentPresence<$ty>,
)+
}
impl $data {
pub fn new_empty() -> $data {
$data {
components: Vec::new(),
families: Vec::new(),
$(
... | if self.$access.has_it() {
b.field(stringify!($access), &self.$access);
}
)+*/
b.finish()
}
}
impl EntityDataHolder for $data {
fn new() -> Self {
$data::new_empty()
... | /*$( | random_line_split |
lib.rs | static str>,
$(
pub $access: ComponentPresence<$ty>,
)+
}
impl $data {
pub fn new_empty() -> $data {
$data {
components: Vec::new(),
families: Vec::new(),
$(
... |
pub fn set_family_relation(&mut self, family: &'static str, ent: Entity) {
match self.families.entry(family) {
Vacant(entry) => {entry.insert(vec!(ent));},
Occupied(entry) => {
let v = entry.into_mut();
if v.contains(&ent) { return; }
... | {
let mut idx: Option<usize> = None;
{
let vec = self.families.get_mut(family).expect("No such family");
let op = vec.iter().enumerate().find(|&(_,e)| *e == ent);
idx = Some(op.expect("Entity not found in this family").0);
}
if let Some(idx) = idx {
... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.