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
utils.py
} -- config file containing data paths and tokenizer information metadata {bool} -- whether the data contains metadata for augmented embeddings proportion {float} -- proportion for splitting up train and test. (default: {0.7}) max_len {int} -- maximum token length for a text. (default: {128}) ...
labels[i] = dataset.iloc[i][label_col] # set parameters for DataLoader -- num_workers = cores params = {'batch_size': 32, 'shuffle': True, 'num_workers': 0 } tokenizer = AutoTokenizer.from_pretrained(vocab) dataset[text_col] = dataset[text_col].app...
'valid': ids[int(total_len * 0.7): ] } for i in dataset.iloc[:, unique_id_col]:
random_line_split
utils.py
} -- config file containing data paths and tokenizer information metadata {bool} -- whether the data contains metadata for augmented embeddings proportion {float} -- proportion for splitting up train and test. (default: {0.7}) max_len {int} -- maximum token length for a text. (default: {128}) ...
else: sequence = np.pad(sequence, (0, max_l - (len(sequence))), 'constant', constant_values=(0)) return sequence def __glove_embed__(sequence, model): """ Embed words in a sequence using GLoVE model """ embedded = [] for word in sequence: embedded.append(model[word]) return e...
sequence = sequence[:max_l]
conditional_block
utils.py
=None, sep='\t') print(dataset) # below fix null values wrecking encode_plus # convert labels to integer and drop nas dataset.iloc[:, label_col] = pd.to_numeric(dataset.iloc[:, label_col], errors = 'coerce' ) dataset = dataset[~ dataset[text_col].isnull()] # recreate the first column with the...
metrics
identifier_name
utils.py
} -- config file containing data paths and tokenizer information metadata {bool} -- whether the data contains metadata for augmented embeddings proportion {float} -- proportion for splitting up train and test. (default: {0.7}) max_len {int} -- maximum token length for a text. (default: {128}) ...
def __glove_embed__(sequence, model): """ Embed words in a sequence using GLoVE model """ embedded = [] for word in sequence: embedded.append(model[word]) return embedded def load_embeddings(config, name, vocab, training_generator, validation_generator): """Load embeddings either from c...
""" Padding function for 1D sequences """ if max_l - len(sequence) < 0: sequence = sequence[:max_l] else: sequence = np.pad(sequence, (0, max_l - (len(sequence))), 'constant', constant_values=(0)) return sequence
identifier_body
ioapic.rs
32 { self.read_reg(0x01) } pub fn read_ioapicarb(&mut self) -> u32 { self.read_reg(0x02) } pub fn read_ioredtbl(&mut self, idx: u8) -> u64 { assert!(idx < 24); let lo = self.read_reg(0x10 + idx * 2); let hi = self.read_reg(0x10 + idx * 2 + 1); u64::from(l...
} impl fmt::Debug for IoApic { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { struct RedirTable<'a>(&'a Mutex<IoApicRegs>); impl<'a> fmt::Debug for RedirTable<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut guard = self.0.lock(); ...
random_line_split
ioapic.rs
(self.mask) << 16) | ((self.trigger_mode as u64) << 15) | ((self.polarity as u64) << 13) | ((self.dest_mode as u64) << 11) | ((self.delivery_mode as u64) << 8) | u64::from(self.vector) } } impl fmt::Debug for IoApic { fn fmt(&self, f: &mut fmt::Format...
{ src_overrides().iter().find(|over| over.bus_irq == irq) }
identifier_body
ioapic.rs
32 { self.read_reg(0x01) } pub fn read_ioapicarb(&mut self) -> u32 { self.read_reg(0x02) } pub fn read_ioredtbl(&mut self, idx: u8) -> u64 { assert!(idx < 24); let lo = self.read_reg(0x10 + idx * 2); let hi = self.read_reg(0x10 + idx * 2 + 1); u64::from(l...
<'a>(&'a Mutex<IoApicRegs>); impl<'a> fmt::Debug for RedirTable<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut guard = self.0.lock(); let count = guard.max_redirection_table_entries(); f.debug_list().entries((0..count).map(|i| g...
RedirTable
identifier_name
handler.go
existing one. CreateServiceInstance(*servicecatalog.Instance) (*servicecatalog.Instance, error) // CreateServiceBinding takes in a (possibly incomplete) // ServiceBinding and will either create or update an // existing one. CreateServiceBinding(*servicecatalog.Binding) (*servicecatalog.Binding, error) DeleteSer...
client := h.newClientFunc(broker.Name, broker.Spec.URL, authUsername, authPassword) // Assign UUID to binding. if in.Spec.OSBGUID == "" { in.Spec.OSBGUID = uuid.NewV4().String() } parameters := make(map[string]interface{}) if in.Spec.Parameters != nil && len(in.Spec.Parameters.Raw) > 0 { err = yaml.Unmarsh...
{ glog.Infof("Creating Service Binding: %v", in) inst, err := instanceForBinding(h.apiClient, in) if err != nil { return nil, err } sc, err := serviceClassForInstance(h.apiClient, inst) if err != nil { return nil, err } broker, err := brokerForServiceClass(h.apiClient, sc) if err != nil { return nil, er...
identifier_body
handler.go
existing one. CreateServiceInstance(*servicecatalog.Instance) (*servicecatalog.Instance, error) // CreateServiceBinding takes in a (possibly incomplete) // ServiceBinding and will either create or update an // existing one. CreateServiceBinding(*servicecatalog.Binding) (*servicecatalog.Binding, error) DeleteSer...
parameters := make(map[string]interface{}) if in.Spec.Parameters != nil && len(in.Spec.Parameters.Raw) > 0 { err = yaml.Unmarshal([]byte(in.Spec.Parameters.Raw), &parameters) if err != nil { glog.Errorf("Failed to unmarshal Binding parameters\n%s\n %v", in.Spec.Parameters, err) return nil, err } } cr...
{ in.Spec.OSBGUID = uuid.NewV4().String() }
conditional_block
handler.go
catalogURLFormatString = "%s/v2/catalog" serviceInstanceFormatString = "%s/v2/service_instances/%s" bindingFormatString = "%s/v2/service_instances/%s/service_bindings/%s" defaultNamespace = "default" ) // Handler defines an interface used as a facade for data access operations. // The contr...
random_line_split
handler.go
kubernetes.Interface apiClient apiclient.APIClient injector injector.BindingInjector newClientFunc func(name, url, username, password string) brokerapi.BrokerClient } func createHandler(k8sClient kubernetes.Interface, client apiclient.APIClient, injector injector.BindingInjector, newClientFn brokerapi.Cre...
CreateServiceBroker
identifier_name
Quirk.ts
} from "../Copy2Clipboard"; export abstract class Quirk { static inputField: HTMLTextAreaElement; static textFields: HTMLFieldSetElement; private readonly name: string; private shortName: string; private id: string; private readonly colorClass: string; input: string; private row: HTM...
(bruh: string): void { this.shortName = bruh; this.id = bruh.toLocaleLowerCase(); } public getShortName(): string { return this.shortName; } public getColorClass(): string { return this.colorClass; } public getTextAreaElement(): HTMLTextAreaElement { re...
setShortName
identifier_name
Quirk.ts
from "../Copy2Clipboard"; export abstract class Quirk { static inputField: HTMLTextAreaElement; static textFields: HTMLFieldSetElement; private readonly name: string; private shortName: string; private id: string; private readonly colorClass: string; input: string; private row: HTMLD...
// Dynamically increase the height of a textarea. static autoSize(element: HTMLTextAreaElement): void { let minHeight: number = parseInt(window.getComputedStyle(element).getPropertyValue("min-height")); element.style.height = "auto"; // Lets the element shrink size. element.style.heig...
{ this.textArea.value = this.input; // Auto resize. Quirk.autoSize(this.textArea); }
identifier_body
Quirk.ts
from "../Copy2Clipboard"; export abstract class Quirk { static inputField: HTMLTextAreaElement; static textFields: HTMLFieldSetElement; private readonly name: string; private shortName: string; private id: string; private readonly colorClass: string; input: string; private row: HTMLD...
this.replaceMatchCase("now", "meow"); this.replaceMatchCase("(per|pre)", "pur"); } applyFishPuns(): void { this.replaceMatchCase("kill", "krill"); this.replaceMatchCase("well", "whale"); this.replaceMatchCase("fine", "fin"); this.replaceMatchCase("see", "sea"); ...
this.replaceMatchCase("cause", "claws");
random_line_split
Quirk.ts
from "../Copy2Clipboard"; export abstract class Quirk { static inputField: HTMLTextAreaElement; static textFields: HTMLFieldSetElement; private readonly name: string; private shortName: string; private id: string; private readonly colorClass: string; input: string; private row: HTMLD...
let visible = !this.row.hidden // Save setting to cookies. setCookieBool(this.id, visible, 31); let optionalCheckboxSet: HTMLDivElement = <HTMLDivElement>document.getElementById(category.tabName.toLocaleLowerCase() + "-optional-checkboxes"); if (visible) { this.up...
{ optionals[i].hidden = !this.activeCheckbox.checked; }
conditional_block
main.py
"cpc": "$CPC$", "pcc": "$PCC$", "drfc": "$D-RFC$", "wpc": "$WPC$" }) df_eval["Critic"] = df_eval["Critic"].replace( to_replace={ "concat": "MLP", "separable": "Separable", "innerprod": "Inner product", "bilinear": "Bilinear" ...
"""Convert results class to a data frame.""" label = "{}, {}, {}".format(nets, critic, loss) rows = list( zip( itertools.repeat(exp_name), itertools.repeat(nets), itertools.repeat(critic), itertools.repeat(loss), itertools.repeat(seed), result.iterat...
identifier_body
main.py
def skew_js_fgan_lower_bound(f): """skewed js lower bound (true cross entropy)""" n = tf.cast(f.shape[0], tf.float32) alpha = 1/n f_diag = tf.linalg.tensor_diag_part(f) first_term = tf.reduce_mean(-tf.nn.softplus(-f_diag)) second_term = (tf.reduce_sum(tf.nn.softplus(f)) - tf.reduce_sum(tf.nn.softplus(f_dia...
raise ValueError('num_masked must be a non-negative integer.')
conditional_block
main.py
n - 1.)) return first_term - second_term @tf.function def infonce_lower_bound(scores): """InfoNCE lower bound from van den Oord et al. (2018).""" nll = tf.reduce_mean(input_tensor=tf.linalg.diag_part(scores) - tf.reduce_logsumexp(input_tensor=scores, axis=1)) mi = tf.math.log(tf.cast(scores.shape[0], tf.float3...
compute_output_shape
identifier_name
main.py
:] return self._bijector_fn(y0, self._input_depth - self._num_masked, **condition_kwargs).inverse_log_det_jacobian( y1, event_ndims=1) def real_nvp_default_template(hidden_layers, shift_only=False, ...
for nets_name, critic_name, loss_name in grid: print("[New experiment] encoder: {}, critic: {}, loss: {}".format( nets_name, critic_name, loss_name))
random_line_split
preprocessing.py
higher than point n. # (i.e. contacts can only decrease when increasing distance) if smooth and mat_n > 2: ir = IsotonicRegression(increasing=False) dist[~np.isfinite(dist)] = 0 dist = ir.fit_transform(range(len(dist)), dist) return dist def get_detectable_bins(mat, n_mads=3, int...
(x): return ss.median_abs_deviation(x, nan_policy="omit") if not inter: if matrix.shape[0] != matrix.shape[1]: raise ValueError("Intrachromosomal matrices must be symmetric.") # Replace nonzero pixels by ones to work on prop. of nonzero pixels matrix.data = np.ones(matrix.data.s...
mad
identifier_name
preprocessing.py
higher than point n. # (i.e. contacts can only decrease when increasing distance) if smooth and mat_n > 2: ir = IsotonicRegression(increasing=False) dist[~np.isfinite(dist)] = 0 dist = ir.fit_transform(range(len(dist)), dist) return dist def get_detectable_bins(mat, n_mads=3, int...
return good_bins def detrend( matrix, detectable_bins=None, max_dist=None, smooth=False, fun=np.nanmean, max_val=10, ): """ Detrends a Hi-C matrix by the distance law. The input matrix should have been normalised beforehandand. Parameters ---------- matrix : scipy...
sum_rows, sum_cols = matrix.sum(axis=1).A1, matrix.sum(axis=0).A1 mad_rows, mad_cols = mad(sum_rows), mad(sum_cols) med_rows, med_cols = np.median(sum_rows), np.median(sum_cols) detect_threshold_rows = max(1, med_rows - mad_rows * n_mads) detect_threshold_cols = max(1, med_cols - mad_col...
conditional_block
preprocessing.py
higher than point n. # (i.e. contacts can only decrease when increasing distance) if smooth and mat_n > 2: ir = IsotonicRegression(increasing=False) dist[~np.isfinite(dist)] = 0 dist = ir.fit_transform(range(len(dist)), dist) return dist def get_detectable_bins(mat, n_mads=3, int...
Returns ------- scipy.sparse.coo_matrix: The detrended Hi-C matrix """ mat = matrix.copy() mu = np.mean(mat.data) sd = np.std(mat.data) mat.data -= mu mat.data /= sd return mat def sum_mat_bins(mat): """ Compute the sum of matrices bins (i.e. rows or columns)...
random_line_split
preprocessing.py
raise ValueError("input type must be scipy.sparse.csr_matrix") # Trim diagonals by removing all elements further than n in the # upper triangle trimmed = sp.tril(mat, n, format="csr") trimmed = sp.triu(trimmed, format="csr") else: trimmed = mat.copy() n_di...
""" Trim an upper triangle sparse matrix so that only the first n diagonals are kept. Parameters ---------- mat : scipy.sparse.csr_matrix or numpy.ndarray The sparse matrix to be trimmed n : int The number of diagonals from the center to keep (0-based). Returns -------...
identifier_body
graph.service.ts
key.SankeyNode<SNodeExtra, SLinkExtra>; export type SLink = d3Sankey.SankeyLink<SNodeExtra, SLinkExtra>; export interface DAG { nodes: SNode[]; links: SLink[]; } // -- Dag Node -- @Injectable({ providedIn: 'root' }) export class GraphService { private docGuids = {}; private docDb: Db = null; private doc...
if (anyChanged || t.column.autoFilterSrc == changedTab.column || (parentChanged && t == changedTab)) { anyChanged = true; // filter child tree GraphFilter.runFilter(t.column); } } //if (anyChanged) this.updateSubject.next(0); ...
var t = tabs[i]; if (!t) continue;
random_line_split
graph.service.ts
key.SankeyNode<SNodeExtra, SLinkExtra>; export type SLink = d3Sankey.SankeyLink<SNodeExtra, SLinkExtra>; export interface DAG { nodes: SNode[]; links: SLink[]; } // -- Dag Node -- @Injectable({ providedIn: 'root' }) export class GraphService { private docGuids = {}; private docDb: Db = null; private doc...
( private messageService: MessageService, private http: HttpClient) { this.addTab("ISO"); } public runFilters(changedTab: GraphTab, parentChanged: boolean) { if (this.runningFilters) return; // prevent re-entry this.runningFilters = true; var tabs = this.graphTabs; ...
constructor
identifier_name
graph.service.ts
, title: v.type }; }); } ) ); } private addToDoc(parent: FullDocNode, input: DocNode2) { var child = new FullDocNode(input); if (parent) { parent.children.push(child); } // Recurse for (var c of input.children) { this.addToDoc(chil...
{ for (var t of this.graphTabs) if (t.anyErrors) return true; return false; }
identifier_body
binomial.rs
algorithm based on the inverse // transformation of the binomial distribution is efficient. Otherwise, // the BTPE algorithm is used. // // Voratas Kachitvichyanukul and Bruce W. Schmeiser. 1988. Binomial // random variate generation. Commun. ACM 31, 2 (February 1988), /...
let mut results = [0.0; 1000];
random_line_split
binomial.rs
; } else if self.p == 1.0 { return self.n; } // The binomial distribution is symmetrical with respect to p -> 1-p, // k -> n-k switch p so that it is less than 0.5 - this allows for lower // expected values we will just invert the result at the end let p = if...
{ self.n - result }
conditional_block
binomial.rs
4) { // Use the BINV algorithm. let s = p / q; let a = ((self.n + 1) as f64) * s; let mut r = q.powi(self.n as i32); let mut u: f64 = rng.gen(); let mut x = 0; while u > r as f64 { u -= r; x += 1; ...
test_binomial
identifier_name
binomial.rs
) -> Binomial { assert!(p >= 0.0, "Binomial::new called with p < 0"); assert!(p <= 1.0, "Binomial::new called with p > 1"); Binomial { n, p } } } /// Convert a `f64` to an `i64`, panicing on overflow. // In the future (Rust 1.34), this might be replaced with `TryFrom`. fn f64_to_i64(x: f64)...
let lambda_l = lambda((f_m - x_l) / (f_m - x_l * p)); let lambda_r = lambda((x_r - f_m) / (x_r * q)); // p1 + area of left tail let p3 = p2 + c / lambda_l; // p1 + area of right tail let p4 = p3 + c / lambda_r; // return value ...
{ a * (1. + 0.5 * a) }
identifier_body
main.rs
( game: &Arc<RwLock<Game>>, user_id: usize, msg: WsMsg, tx: &mpsc::UnboundedSender<WsMsg> ) -> Result<()> { match msg { WsMsg::Login(username) => { if game.read().await.players.len() >= MAX_N_PLAYERS { tx.send(WsMsg::LoginRejected(LoginRejectedReason::GameIsFull))?; return Ok(()) } if game.read(...
load_deck
identifier_name
main.rs
#{}", round.czar); // Distribute cards and notify players self.distribute_cards(); for (id, player) in &mut self.players { let role = if *id == round.czar { Role::Czar } else { Role::Player }; self.clients[id].send(WsMsg::NewRound { role, prompt: round.prompt.clone(), hand: player.hand.clone()...
{ let game = &mut *game.write().await; game.clients.remove(&user_id); if let Some(player) = game.players.remove(&user_id) { // Discard player's answers game.answers.discard(&player.hand); // Discard player's submitted answers, if any let mut user_is_czar = false; if let Game { answers, round: Some(...
identifier_body
main.rs
} // Find next czar let mut player_ids = self.players.keys().collect::<Vec<_>>(); player_ids.sort_unstable(); if let Err(idx) = player_ids.binary_search(&&next_czar) { // There's no player with ID next_czar if idx == player_ids.len() { // There isn't a greater key next_czar = *player_ids[0]; ...
}, } // Check whether all players have answered if round.answers.len() == players.len() - 1 { round.state = RoundState::Judging; // If so, notify them that JUDGEMENT HAS BEGUN // TODO maybe obfuscate the player IDs before sending for id in players.keys() { clients[id].send(Ws...
random_line_split
cougballoon_rcv.py
, 'Hours':RMChours, 'Minutes':RMCminutes, 'Seconds':RMCseconds},'External temperature(deg F)':extTemp, 'Internal temperature(deg F)':intTemp, 'Video Transmitter temperature(deg F)':vidTemp, 'Carbon Monoxide level(ppm)':COlevel, 'Methane level(ppm)':CH4level, 'HackHD camera statuses':HackStatus } ] data_string = json....
#trace11 = Scatter( # x=[], # y=[], # mode='lines+markers', # stream=stream11
random_line_split
cougballoon_rcv.py
(nmeaString): #Commented out lines are for .docs, we are using .txt files instead. #f = open('/Users/michaelhamilton/gpsbabel/nmeaRawData.doc', 'a') f = open('/Users/michaelhamilton/gpsbabel/nmeaRawData.txt', 'a') f.write(nmeaString) f.close() saveAllIncomingData(nmeaString) #os.system("cd /Users/michaelh...
handleGPSdata
identifier_name
cougballoon_rcv.py
#Save all incoming data with a current date/time string def saveData(a): x = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f') saveAllIncomingData(x) saveAllIncomingData(a) #Convert GPS strings to floats (Couldn't get str.isnumeric() to work correctly) def StringToFloatGPS(a): a = a.rstrip('\n'); ...
hours = hours.rstrip('\n'); hours = hours.rstrip('\r'); hours = int(hours) + 17 if (hours > 24): hours = hours - 24 hours = str(hours) return hours
identifier_body
cougballoon_rcv.py
mode='lines+markers', stream=stream2 ) trace3 = Scatter( x=[], y=[], mode='lines+markers', stream=stream3 ) trace4 = Scatter( x=[], y=[], mode='lines+markers', stream=stream4 ) trace5 = Scatter( x=[], y=[], mode='lines+markers', stream=stream5 ) trace6 = Scatte...
print "Altitude(from press/temp):" print line y = StringToFloat(line, pressureAltitude) saveData(line) pressureAltitude = y print y s4.write(dict(x=x, y=y))
conditional_block
options.go
option() } // Options is a list of Option values that also satisfies the Option interface. // Helper comparison packages may return an Options value when packing multiple // Option values into a single Option. When this package processes an Options, // it will be implicitly expanded into a flat list. // // Applying a...
() {} func (o option) String() string { // TODO: Add information about the caller? // TODO: Maintain the order that filters were added? var ss []string switch op := o.op.(type) { case *transformer: fn := getFuncName(op.fnc.Pointer()) ss = append(ss, fmt.Sprintf("Transformer(%s, %s)", op.name, fn)) case *com...
option
identifier_name
options.go
option() } // Options is a list of Option values that also satisfies the Option interface. // Helper comparison packages may return an Options value when packing multiple // Option values into a single Option. When this package processes an Options, // it will be implicitly expanded into a flat list. // // Applying a...
name = name[i+1:] // E.g., "mypkg.(mytype).myfunc" } return name } // FilterPath returns a new Option where opt is only evaluated if filter f // returns true for the current Path in the value tree. // // The option passed in may be an Ignore, Transformer, Comparer, Options, or // a previously filtered Option. func...
{ fnc := runtime.FuncForPC(p) if fnc == nil { return "<unknown>" } name := fnc.Name() // E.g., "long/path/name/mypkg.(mytype).(long/path/name/mypkg.myfunc)-fm" if strings.HasSuffix(name, ")-fm") || strings.HasSuffix(name, ")·fm") { // Strip the package name from method name. name = strings.TrimSuffix(name, "...
identifier_body
options.go
"runtime" "strings" ) // Option configures for specific behavior of Equal and Diff. In particular, // the fundamental Option functions (Ignore, Transformer, and Comparer), // configure how equality is determined. // // The fundamental options may be composed with filters (FilterPath and // FilterValues) to control t...
import ( "fmt" "reflect"
random_line_split
options.go
option() } // Options is a list of Option values that also satisfies the Option interface. // Helper comparison packages may return an Options value when packing multiple // Option values into a single Option. When this package processes an Options, // it will be implicitly expanded into a flat list. // // Applying a...
name := fnc.Name() // E.g., "long/path/name/mypkg.(mytype).(long/path/name/mypkg.myfunc)-fm" if strings.HasSuffix(name, ")-fm") || strings.HasSuffix(name, ")·fm") { // Strip the package name from method name. name = strings.TrimSuffix(name, ")-fm") name = strings.TrimSuffix(name, ")·fm") if i := strings.Last...
{ return "<unknown>" }
conditional_block
combat.rs
20); NewState::Player } pub fn ranged_attack( ecs: &mut World, map: &mut Map, attacker: Entity, victim: Entity, ranged_power: i32, ) { let mut attacker_pos = None; let mut victim_pos = None; // Find positions for the start and end if let Ok(ae) = ecs.entry_ref(attacker) { ...
( ecs: &mut World, commands: &mut CommandBuffer, dead_entities: Vec<Entity>, splatter: &mut Option<RGB>, ) { dead_entities.iter().for_each(|entity| { crate::stats::record_death(); let mut was_decor = false; let mut was_player = false; if let Ok(mut er) = ecs.entry_mut...
kill_things
identifier_name
combat.rs
20); NewState::Player } pub fn ranged_attack( ecs: &mut World, map: &mut Map, attacker: Entity, victim: Entity, ranged_power: i32, )
// Set state for the projectile path let mut power = ranged_power; let mut range = 0; let mut projectile_path = Vec::new(); let mut splatter = None; let mut commands = CommandBuffer::new(ecs); let current_layer = attacker_pos.layer; // Map of entity locations. Rebuilt every time becaus...
{ let mut attacker_pos = None; let mut victim_pos = None; // Find positions for the start and end if let Ok(ae) = ecs.entry_ref(attacker) { if let Ok(pos) = ae.get_component::<Position>() { attacker_pos = Some(pos.clone()); } } if let Ok(ae) = ecs.entry_ref(victim) {...
identifier_body
combat.rs
20); NewState::Player } pub fn ranged_attack( ecs: &mut World, map: &mut Map, attacker: Entity, victim: Entity, ranged_power: i32, ) { let mut attacker_pos = None; let mut victim_pos = None; // Find positions for the start and end if let Ok(ae) = ecs.entry_ref(attacker) { ...
// If necessary, kill them. let mut commands = CommandBuffer::new(ecs); let mut splatter = None; kill_things(ecs, &mut commands, dead_entities, &mut splatter); // Splatter blood. It's good for you. } fn kill_things( ecs: &mut World, commands: &mut CommandBuffer, dead_entities: Vec<En...
{ if let Ok(hp) = v.get_component_mut::<Health>() { hp.current = i32::max(0, hp.current - melee_power); if hp.current == 0 { dead_entities.push(victim); } } if let Ok(blood) = v.get_component::<Blood>() { let idx = map.get_layer(dpo...
conditional_block
combat.rs
20); NewState::Player } pub fn ranged_attack( ecs: &mut World, map: &mut Map, attacker: Entity, victim: Entity, ranged_power: i32, ) { let mut attacker_pos = None; let mut victim_pos = None; // Find positions for the start and end if let Ok(ae) = ecs.entry_ref(attacker) { ...
}, Glyph { glyph: to_cp437('*'), color: ColorPair::new(RED, BLACK), }, )); commands.flush(ecs); } pub fn hit_tile_contents( ecs: &mut World, pt: Point, layer: u32, commands: &mut CommandBuffer, splatter: &mut Option<RGB>, power: i32, ) ->...
layer: current_layer as usize,
random_line_split
tutor-details.component.ts
requestPermissions:{google:['https://www.googleapis.com/auth/calendar']}, forceApprovalPrompt: {google: true}, requestOfflineToken: {google: true}}); Stripe.setPublishableKey(Meteor.settings.public.stripe.livePublishableKey); var handler = StripeCheckout.configure({ key: Meteor.settings.public.stripe.tes...
private myDatePickerOptions: IMyOptions = { // other options... dateFormat: 'dd.mm.yyyy', inline: true, disableDateRanges: [{ begin: {year: this.today.getFullYear(), month: this.today.getMonth()-2, day: this.today.getDate()}, end: {year: this.today.getFullYear(), month: th...
{}
identifier_body
tutor-details.component.ts
({requestPermissions:{google:['https://www.googleapis.com/auth/calendar']}, forceApprovalPrompt: {google: true}, requestOfflineToken: {google: true}}); Stripe.setPublishableKey(Meteor.settings.public.stripe.livePublishableKey); var handler = StripeCheckout.configure({ key: Meteor.settings.public.stripe.t...
(): void{ this.checkout = false; } GoToCheckOut(): void{ // if(!this.user_skype_email){ // alert('Please enter your skype username so the teatch can contact you :)'); // }else{ // alert('you are now registered in this class :)'); // } console.log(this.slot); console.log(this.tut...
step1
identifier_name
tutor-details.component.ts
requestPermissions:{google:['https://www.googleapis.com/auth/calendar']}, forceApprovalPrompt: {google: true}, requestOfflineToken: {google: true}}); Stripe.setPublishableKey(Meteor.settings.public.stripe.livePublishableKey); var handler = StripeCheckout.configure({ key: Meteor.settings.public.stripe.tes...
else if(this.tutorSchedule[this.day][i]==1){ this.tutorSchedule[this.day][i]=0; this.colorsSched[this.day][i]='blue'; } // else if(this.colorsSched[this.day][i]='blue'){ // this.colorsSched[this.day][i]='green'; // } } onDateChanged(event: IMyDateModel) { let _MS_PER_DAY = 1000 * ...
{ this.tutorSchedule[this.day][i]=1; this.colorsSched[this.day][i]='green'; }
conditional_block
tutor-details.component.ts
({requestPermissions:{google:['https://www.googleapis.com/auth/calendar']}, forceApprovalPrompt: {google: true}, requestOfflineToken: {google: true}}); Stripe.setPublishableKey(Meteor.settings.public.stripe.livePublishableKey); var handler = StripeCheckout.configure({ key: Meteor.settings.public.stripe.t...
console.log('payment form valid') Stripe.card.createToken({ number: this.payment_form.value.cardNumber, cvc: this.payment_form.value.cvc, exp_month: this.payment_form.value.expiryMonth, exp_year: this.payment_form.value.expiryYear }, function(status, response) { ...
} } CheckoutFn():void{ if (this.payment_form.valid) {
random_line_split
lib.go
pongWait = 60 * time.Second // Send pings to client with this period. Must be less than pongWait. pingPeriod = (pongWait * 9) / 10 // Time allowed to write the file to the client. writeWait = 10 * time.Second ) // Event types const ( EVENT_CONNECT = iota EVENT_ROAMING EVENT_DISCONNECT EVENT_LEVEL ) type Le...
const ( // Time allowed to read the next pong message from the client.
random_line_split
lib.go
.Time sync.RWMutex ReportChan chan ReportEvent } type LeaseList struct { List []LeaseEntry sync.RWMutex } type ConfMikrotik struct { Address string `yaml:"address"` Username string `yaml:"username"` Password string `yaml:"password"` Interval time.Duration `yaml:"interval"` Mode str...
func FindLeaseByMAC(list []LeaseEntry, mac string) (e LeaseEntry, ok bool) { for _, e := range list { if e.MAC == mac { return e, true } } return } func RTLoop(c *routeros.Client, conf *Config) { for { cmd := "/caps-man/registration-table/print" if strings.ToLower(config.Router.Mode) == "wifi" { cm...
{ ticker := time.NewTicker(config.DHCP.Interval) for { // nolint:gosimple select { case <-ticker.C: l, err := GetDHCPLeases(config.DHCP.Address, config.DHCP.Username, config.DHCP.Password) if err != nil { log.WithFields(log.Fields{"dhcp-addr": config.DHCP.Address}).Error("Error reloading DHCP Leases: ",...
identifier_body
lib.go
time.Time sync.RWMutex ReportChan chan ReportEvent } type LeaseList struct { List []LeaseEntry sync.RWMutex } type ConfMikrotik struct { Address string `yaml:"address"` Username string `yaml:"username"` Password string `yaml:"password"` Interval time.Duration `yaml:"interval"` Mode ...
() { } // Handle report update request func (b *BroadcastData) reportUpdate(report []ReportEntry) error { output, err := json.Marshal(report) if err != nil { return err } // Lock mutex b.RLock() defer b.RUnlock() // Prepare new list of entries rm := map[string]ReportEntry{} for _, v := range report { r...
usage
identifier_name
lib.go
"wifi" { cmd = "/interface/wireless/registration-table/print" } reply, err := c.Run(cmd) if err != nil { log.WithFields(log.Fields{"address": config.Router.Address, "username": config.Router.Username}).Error("Error during request to CapsMan server: ", err) // Try to close connection c.Close() /...
{ if (len(dev.OnLevel.HttpPost) > 0) || (len(dev.OnLevel.HttpGet) > 0) { go makeRequest(dev.OnLevel, map[string]string{ "name": dev.Name, "mac": data.Old.MAC, "roaming.to": "", "roaming.from": "", "level.from": data.Old.Signal, "level.to": da...
conditional_block
uiTools.js
allPossibleKesmNames', function() { return KesmNames.find().map(function(doc) { return doc.kesmName; }); }); }); getAllDataForKesmName = function(kesmName) { var properties = {}; if (propertyCollections && _.has(propertyCollections, kesmName)) { _.each(propertyCollections[kesmName].find().fetch(), functi...
Template.registerHelper('data', function(data) { return data.hash; }); Meteor.cb = function(e,r) { if (e) console.error(e); if(r) { if (_.isArray(r) && console.table) { console.table(r); } else { console.log(r); } } }; guiUtils = {}; guiUtils.makeMeteorReactiveTextBox = function(textI...
// {{> controllerTemplate}} // {{/with}}
random_line_split
uiTools.js
PossibleKesmNames', function() { return KesmNames.find().map(function(doc) { return doc.kesmName; }); }); }); getAllDataForKesmName = function(kesmName) { var properties = {}; if (propertyCollections && _.has(propertyCollections, kesmName)) { _.each(propertyCollections[kesmName].find().fetch(), function(...
if (tbQuery) { $(textInputQuery).val(tbQuery.value); } }; // Call this first when the slider is initialized, and when changes happen Tracker.autorun(updateTextBoxFromMeteor); // jQuery-ui -> Meteor var pushTextChangeToMeteor = function() { var currentValue = $(textInputQuery).val(); ...
{ return; }
conditional_block
BatteryMonitor6813Tester.go
TC6813.New(spiConnection, 2).Initialise() // // } ltc_lock.Lock() defer ltc_lock.Unlock() for
chainLength-- if chainLength > 0 { ltc = LTC6813.New(spiConnection, chainLength) if err := ltc.Initialise(); err != nil { fmt.Print(err) log.Fatal(err) } _, err := ltc.MeasureVoltages() if err != nil { fmt.Println("MeasureVoltages - ", err) } _, err = ltc.MeasureTemperatures() if err != nil ...
{ testLtc := LTC6813.New(spiConnection, chainLength) if _, err := testLtc.Test(); err != nil { fmt.Println(err) break } testLtc = nil chainLength++ }
conditional_block
BatteryMonitor6813Tester.go
{ nDevices, err = getLTC6813() if err != nil { fmt.Print(err) nErrors++ return } } if nDevices == 0 { fmt.Printf("\033cNo devices found on %s - %s", *spiDevice, time.Now().Format("15:04:05.99")) return } banks, err = ltc.MeasureVoltagesSC() if err != nil { // Retry if it failed and ignore the...
/** WEB service to read the current from the I2C port */ func getI2CCurrent(w http.ResponseWriter, r *http.Request) {
random_line_split
BatteryMonitor6813Tester.go
TC6813.New(spiConnection, 2).Initialise() // // } ltc_lock.Lock() defer ltc_lock.Unlock() for { testLtc := LTC6813.New(spiConnection, chainLength) if _, err := testLtc.Test(); err != nil { fmt.Println(err) break } testLtc = nil chainLength++ } chainLength-- if chainLength > 0 { ltc = LTC6813....
(*sql.DB, error) { if pDB != nil { _ = pDB.Close() pDB = nil } var sConnectionString = *pDatabaseLogin + ":" + *pDatabasePassword + "@tcp(" + *pDatabaseServer + ":" + *pDatabasePort + ")/" + *pDatabaseName fmt.Println("Connecting to [", sConnectionString, "]") db, err := sql.Open("mysql", sConnectionString) ...
nnectToDatabase()
identifier_name
BatteryMonitor6813Tester.go
LTC6813.New(spiConnection, 2).Initialise() // // } ltc_lock.Lock() defer ltc_lock.Unlock() for { testLtc := LTC6813.New(spiConnection, chainLength) if _, err := testLtc.Test(); err != nil { fmt.Println(err) break } testLtc = nil chainLength++ } chainLength-- if chainLength > 0 { ltc = LTC681...
select { case <-done: return case <-ticker.C: performMeasurements() } } }() // Configure and start the WEB server router := mux.NewRouter().StrictSlash(true) router.HandleFunc("/", getValues).Methods("GET") router.HandleFunc("/version", getVersion).Methods("GET") router.HandleFunc("/i2cre...
if !*verbose { log.SetOutput(ioutil.Discard) } log.SetFlags(log.Lmicroseconds) if flag.NArg() != 0 { return errors.New("unexpected argument, try -help") } for { nDevices, err := getLTC6813() if err == nil && nDevices > 0 { break } fmt.Println("Looking for a device") } done := make(chan bool) ti...
identifier_body
image_caption.py
# Loading cap as values and images as key in dictionary tok = {} for item in range(len(cap)-1): tem = cap[item].split("#") #tem[0]= imgname.jpg ..... tem[1]=0 captionn. if tem[0] in tok: tok[tem[0]].append(tem[1][2:]) else: tok[tem[0]] = [tem[1][2:]] #tem[n]= imgName ... #tok[tem[n...
x_training = open(training_path, 'r').read().split("\n") x_valid = open(valid_path, 'r').read().split("\n") x_testing = open(testing_path , 'r').read().split("\n")
random_line_split
image_caption.py
flickr_8k_val_dataset.txt','wb') valid_dataset.write(b"image_id\tcap\n") testing_dataset = open('flickr_8k_test_dataset.txt','wb') testing_dataset.write(b"image_id\tcap\n") # Loading image ids and captions for each of these images in the above 3 files for img in x_training: if img == '': continue...
image = preprocess(img) pred = model.predict(image).reshape(2048) return pred
identifier_body
image_caption.py
") x_valid = open(valid_path, 'r').read().split("\n") x_testing = open(testing_path , 'r').read().split("\n") # Loading cap as values and images as key in dictionary tok = {} for item in range(len(cap)-1): tem = cap[item].split("#") #tem[0]= imgname.jpg ..... tem[1]=0 captionn. if tem[0] in tok: ...
testing_dataset.close() for img in x_valid: if img == '': continue for capt in tok[img]: caption = "<start> "+ capt + " <end>" valid_dataset.write((img+"\t"+caption+"\n").encode()) valid_dataset.flush() valid_dataset.close() # Here, we're using ResNet50 Model from...
if img == '': continue for capt in tok[img]: caption = "<start> "+ capt + " <end>" testing_dataset.write((img+"\t"+caption+"\n").encode()) testing_dataset.flush()
conditional_block
image_caption.py
lickr_8k_train_dataset.txt','wb') training_dataset.write(b"image_id\tcap\n") valid_dataset = open('flickr_8k_val_dataset.txt','wb') valid_dataset.write(b"image_id\tcap\n") testing_dataset = open('flickr_8k_test_dataset.txt','wb') testing_dataset.write(b"image_id\tcap\n") # Loading image ids and captions for...
get_encode
identifier_name
idempotent.rs
// we always receive `[x, n] as a` // .. // (v-- chut' ne udalil :lol:, podumal wo hn9, A NE-NE-NE) //> ... SO, if "fn" mutate own args, and computation which "generate new value, // to update old value in args (in case of [] is some "next-empty-cell" in arr, and `len`) // is base...
} fn fetchOrders(userId) { ajax( "http://some.api/orders/" + userId, fn onOrders(orders) { for (let i = 0; i < orders.length; i++) { // keep a reference to latest order for each user users[userId].latestOrder = orders[i]; userOrders[orders[i].o...
users[userId] = userData; });
random_line_split
idempotent.rs
// not IDEMPOTENT because: *WRONG: we update, and/but not completly rewrite `x`, // *RIGHT: mut_aliasing (our computed value for `x` rely on mut_aliased `x`) // (BUT) // BTW(p.s.)--v: `some_fn` break rule: /// "mutate only TREE_in_the_WOOD , emit "own_copied/immutabl" value" // ...
{ x += n*x }
identifier_body
idempotent.rs
(a = [], n) { a.push(n) } // ^-- here was: "ADD value, not just change." // BUT actually .. it's also can be considered as MUT_alising .. since result of `push` // depends of `a`, .. and if we call 2 times `some_fn` of course it's gives different sideeff, // since its computation based on MUTated value,...
some_fn
identifier_name
core_convert.py
# TODO: MAP THIS ?: 4, # Grekiskt # TODO: MAP THIS ?: 5, # Indien # TODO: MAP THIS ?: 6, # Nordamerika # TODO: MAP THIS ?: 7, # Latinamerika # TODO: MAP THIS ?: 8, # Orienten # TODO: MAP THIS ?: 9, # Japan # TODO: MAP THIS ?: 10, # Italienskt # TODO: MAP T...
== product.article.gtin: return next_lower_article.quantity_of_lower_layer * upper_quantity return None def convert_u
conditional_block
core_convert.py
'5+ dagar': 2197, '7+ dagar': 2200, '10+ dagar': 2203, '30+ dagar': 2206, 'Svenskt ursprung': 2209, 'Svensk fågel': 2212, '4+ dagar': 2215, 'Vegansk': 2218, 'MSC': 2219, 'Strategisk produkt': 2222, 'Svenskt sigill klimatcertifierad'...
'Ekonomipack': 1, 'Nyckelhålsmärkt': 1736, 'Ekologisk': 2167, 'Glutenfri': 2168, 'Laktosfri': 2169, 'Låglaktos': 2170, 'Premiumkvalité': 2171, 'Mjölkproteinfri': 2172, # 'Nyhet': 2173, '18Åldersgräns': 2174, 'Fairtrade': 2175, ...
identifier_body
core_convert.py
: MAP THIS ?: 10, # Italienskt # TODO: MAP THIS ?: 11, # Sydostasien # TODO: MAP THIS ?: 12, # Spansk # TODO: MAP THIS ?: 13, # Tyskland # TODO: MAP THIS ?: 14, # "Ryssland och Östeuropa" # TODO: MAP THIS ?: 15, # Internationellt # TODO: MAP THIS ?: 16, # Övriga #...
"H87": 1, # st, PIECES "GRM": 2, # g, WEIGHT "KGM": 3, # kg, WEIGHT "DLT": 6, # dl, VOLUME "LTR": 7, # L, VOLUME
random_line_split
core_convert.py
able = { "Crossdocking": "X", "Nightorder": "A", } return table[key] if key in table else None def get_attribute_id(key): # data from prefilledautomaten.attribute table = { 'Ekonomipack': 1, 'Nyckelhålsmärkt': 1736, 'Ekologisk': 2167, 'Glutenfri': 2168, ...
r_route_from_product_type(key): t
identifier_name
parser.go
/juniperUDP/port" "github.com/golang/protobuf/proto" _"strings" ) // JuniperUDPParser is an object for Parsing incoming metrics. type JuniperUDPParser struct { // DefaultTags will be added to every parsed metric DefaultTags map[string]string } /* func (p *JuniperUDPParser) ParseWithDefaultTimePrecision(buf []byte...
random_line_split
parser.go
uniperUDP/npu_utilization" _"github.com/influxdata/telegraf/plugins/parsers/juniperUDP/optics" _"github.com/influxdata/telegraf/plugins/parsers/juniperUDP/packet_stats" _"github.com/influxdata/telegraf/plugins/parsers/juniperUDP/port_exp" _"github.com/influxdata/telegraf/plugins/parsers/juniperUDP/port" "github.co...
"fabricMessageExt" : "/junos/system/linecard/fabric", "jnpr_firewall_ext" : "/junos/system/linecard/firewall/", "jnprLogicalInterfaceExt" : "/junos/system/linecard/interface/logical/usage/", "npu_memory_ext" : "/junos/system/linecard/npu/memory/",...
{ //out, _ := os.Create("telegraf_udp.log") dir, err := filepath.Abs(filepath.Dir(os.Args[0])) if err != nil { log.Fatal(err) } path := dir+"/logs" if _, err := os.Stat(path); os.IsNotExist(err) { os.Mkdir(path, 0777) } out, errFile := os.OpenFile("logs/telegraf_udp.log", os.O_APPEND|os....
identifier_body
parser.go
.HasTag(k) { m.AddTag(k, v) } } } } return metrics, err } */ func parseArray(data []interface{}, masterKey string) []interface{} { var arrData []interface{} for _,val := range data{ valType := reflect.ValueOf(val).Kind() if valType == reflect.Map{ mapD...
{ var fields map[string]interface{} if reflect.ValueOf(sensorData).Kind() == reflect.Map { _ = sensorName sensorName = key[1:len(key)-1] var measurementName string measurementName = sensorName /* if val, ok := sensorMapping[sensorName]; ok { measurementName = val } else { measuremen...
conditional_block
parser.go
_aa] = value_aa } finalData = append(finalData, make(map[string]interface{})) for k,v := range leafTmp{ finalData[len(finalData)-1].(map[string]interface{})[k] = v ...
SetDefaultTags
identifier_name
alain.js
resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.buildAlain = exports.addValueToVariable = exports.addProviderToModule = exports.addIm...
ct) { var _a; if (schema.path === undefined) { schema.path = `/${path.join(project.sourceRoot, (_a = alainProject === null || alainProject === void 0 ? void 0 : alainProject.routesRoot) !== null && _a !== void 0 ? _a : 'app/routes')}`; } } exports.refreshPathRoot = refreshPathRoot; function resolveS...
ema, alainProje
identifier_name
alain.js
? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.buildAlain = exports.addValueToVariable = exports.addProviderToModule = exports.add...
= true) { const source = (0, ast_1.getSourceFile)(tree, filePath); const node = (0, ast_utils_1.findNode)(source, ts.SyntaxKind.Identifier, variableName); if (!node) { throw new schematics_1.SchematicsException(`Could not find any [${variableName}] variable in path '${filePath}'.`); } // es...
ce, filePath, serviceName, importPath); const declarationRecorder = tree.beginUpdate(filePath); changes.forEach(change => { if (change.path == null) return; if (change instanceof change_1.InsertChange) { declarationRecorder.insertLeft(change.pos, change.toAdd); } ...
identifier_body
alain.js
? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.buildAlain = exports.addValueToVariable = exports.addProviderToModule = exports.add...
} // module name if (schema.module) { ret.push(schema.module); } // target name if (schema.target) { ret.push(...schema.target.split('/')); } // name ret.push(core_1.strings.dasherize(schema.name)); return ret.join('-'); } function buildName(schema, prefix) { ...
{ ret.push(projectPrefix); }
conditional_block
alain.js
? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.buildAlain = exports.addValueToVariable = exports.addProviderToModule = exports.add...
schema.service === 'ignore' ? (0, schematics_1.filter)(filePath => !filePath.endsWith('.service.ts.template')) : (0, schematics
// Don't support inline schema.inlineTemplate = false; const templateSource = (0, schematics_1.apply)((0, schematics_1.url)(schema._filesPath), [ (0, schematics_1.filter)(filePath => !filePath.endsWith('.DS_Store')),
random_line_split
plot.py
.png') # Display to screen plt.show() def
(_band, _period): """ Plots an observed band using pyplot :param _band: Array to be plotted :param _period: Period of object """ # Frequency = 1 / Period _freq = 1 / _period _xfit, _lobf = calclobf(_band, _period) # Plot the data in the array to screen, lightly coloured and z rank be...
plotband
identifier_name
plot.py
first empty row of the array _smallstar = np.delete(_smallstar, 0, axis=0) # Determine the luminosity and effective temperature of each star _luma, _lumaerr, _wiena = getwientemp(_largestar, _distance, _derr, 1) _lumb, _lumberr, _wienb = getwientemp(_smallstar, _distance, _derr, 2) # Calculate lu...
for _line in _file: # Split each line into constituent values _x = _line.split() # Append data array with each value, converted to float, convert parallax angle to distance _data = np.append(_data, np.array([float(_x[1]), float(_x[2]), (1 / float(_x[3]))], ndmin=2), axis=0)
random_line_split
plot.py
.png') # Display to screen plt.show() def plotband(_band, _period): """ Plots an observed band using pyplot :param _band: Array to be plotted :param _period: Period of object """ # Frequency = 1 / Period _freq = 1 / _period _xfit, _lobf = calclobf(_band, _period) # Plot the...
# Delete first empty row of the array _largestar = np.delete(_largestar, 0, axis=0) # Determine the spectral flux density from the small star i = 0 while i < 5: # Determine the maximum and minimum values of the observed band _max, _min = lightcurve.maxminvals(_bands[i]) # S...
_max, _min = lightcurve.maxminvals(_bands[i]) # The large star uses the maximum flux value (smallest magnitude) _largestar = np.append(_largestar, np.array([_lambda[i], (magtoflux(_min, i))], ndmin=2), axis=0) i += 1
conditional_block
plot.py
def plotallbands(_zband, _yband, _jband, _hband, _kband, _period): """ Plots all observed bands to the same graph :param _zband: Observed z-band :param _yband: Observed y-band :param _jband: Observed j-band :param _hband: Observed h-band :param _kband: Observed k-band :param _period: ...
""" Rounds the provided value to 2 significant figures :param _val: Value to be rounded :return: Float, original value rounded to 2 significant figures """ return round(_val, 3 - int(floor(log10(abs(_val)))) - 1)
identifier_body
routing.rs
nodes, we know our incoming edges have already been updated to point to the egress nodes. let mut ingresses = HashMap::new(); for node in topo_list { let domain = graph[node].domain(); // First, we add egress nodes for any of our cross-domain children let children: Vec<_> = graph.neig...
{ // ensure all egress nodes contain the tx channel of the domains of their child ingress nodes for &node in new { let n = &graph[node]; if let node::Type::Ingress = **n { // check the egress connected to this ingress } else { continue; } for egr...
identifier_body
routing.rs
*graph); while let Some(node) = topo.next(&*graph) { if node == source { continue; } if !new.contains(&node) { continue; } topo_list.push(node); } // we need to keep track of all the times we change the parent of a node (by replacing it with ...
connect
identifier_name
routing.rs
domain::Index, HashMap<NodeIndex, NodeIndex>> { // find all new nodes in topological order. we collect first since we'll be mutating the graph // below. it's convenient to have the nodes in topological order, because we then know that // we'll first add egress nodes, and then the related ingress nodes. if ...
let was_materialized = graph.remove_edge(old).unwrap(); graph.add_edge(ingress, node, was_materialized); // tracking swaps here is a bit tricky because we've already swapped the "true" parents
random_line_split
main.rs
*response.body_mut() = Body::wrap_stream(stream_fuck); //*response.body_mut() = Body::empty(); //*response.set_body(Box::new(stream)); // type BoxFut = Box<Future<Item = Response<Body>, Error = hyper::Error> + Send>; //let future_result = future::ok(response); ...
{ /* extern crate openssl; println!("===== testOpenSSL ====="); use openssl::ssl::{SslConnector, SslMethod}; use std::io::{Read, Write}; use std::net::TcpStream; let connector = SslConnector::builder(SslMethod::tls()).unwrap().build(); let stream = TcpStream::connect("google.com:443")....
identifier_body
main.rs
(uri: &Uri) -> String { //let in_addr: SocketAddr = get_in_addr(); let uri_string = uri.path_and_query().map(|x| x.as_str()).unwrap_or(""); //let uri: String = uri_string.parse().unwrap(); //let in_uri_string = format!("http://{}/{}", in_addr, req.uri()); let in_remove_string = "/fwd/"; debug!(...
reduce_forwarded_uri
identifier_name
main.rs
ut { fn echo(req: Request<Body>) -> BoxFut { let mut response = Response::new(Body::empty()); debug!("method: {}, uri: {}", req.method(), req.uri()); match req.method() { &Method::GET => { if req.uri().path().starts_with("/fwd/") { let req_uri = reduce_forwarded_uri(req....
random_line_split
mod.rs
::Always), _ => Err("invalid cache policy"), } } } impl Default for CachePolicy { fn default() -> Self { CachePolicy::Auto } } /// Options that configure the behavior of the passthrough fuse file system. #[derive(Debug, Clone, PartialEq)] pub struct Config { /// How long th...
unsafe { libc::openat(dfd, pathname.as_ptr(), flags) } };
conditional_block
mod.rs
use std::mem::MaybeUninit; use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; use std::str::FromStr; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Mutex, MutexGuard, RwLock, RwLockWriteGuard}; use std::time::Duration; use vm_memory::ByteValued; use crate::abi::linux_abi as fuse; use ...
use std::ffi::{CStr, CString}; use std::fs::File; use std::io; use std::marker::PhantomData;
random_line_split
mod.rs
fd from // `inodes` into one that can go into `handles`. This is accomplished by reading the // `self/fd/{}` symlink. We keep an open fd here in case the file system tree that we are meant // to be serving doesn't have access to `/proc`. proc: File, // Whether writeback caching is enabled for this...
elease(&se
identifier_name
mod.rs
keyBTreeMap<Inode, InodeAltKey, Arc<InodeData>>> { self.inodes.write().unwrap() } fn insert(&self, inode: Inode, altkey: InodeAltKey, data: InodeData) { self.inodes .write() .unwrap() .insert(inode, altkey, Arc::new(data)); } } struct HandleData { in...
impl Default for CachePolicy { fn default() -> Self { CachePolicy::Auto } } /// Options that configure the behavior of the passthrough fuse file system. #[derive(Debug, Clone, PartialEq)] pub struct Config { /// How long the FUSE client should consider directory entries to be valid. If the contents...
match s { "never" | "Never" | "NEVER" | "none" | "None" | "NONE" => Ok(CachePolicy::Never), "auto" | "Auto" | "AUTO" => Ok(CachePolicy::Auto), "always" | "Always" | "ALWAYS" => Ok(CachePolicy::Always), _ => Err("invalid cache policy"), } } }
identifier_body
CollectGame.js
cookie('collect_high_score') != '') { this.high_score = $.cookie('collect_high_score'); } }, create: function() { console.log('Collect game'); this.background_music = this.game.add.audio('boss_background_music'); this.right_answer_sound = this.game.add.audio('right_answer_sound'); this.wrong_answer_soun...
} if (this.answer == answer) {
{ this.score = 0; }
conditional_block
CollectGame.js
$.cookie('collect_high_score') != '') { this.high_score = $.cookie('collect_high_score'); } }, create: function() { console.log('Collect game'); this.background_music = this.game.add.audio('boss_background_music'); this.right_answer_sound = this.game.add.audio('right_answer_sound'); this.wrong_answer_s...
//boulder.value = this.boulderVal; //console.log('VALUE: ' + boulder.value); //console.log('boulder'); //boulder_text = this.game.add.text(15, 15, boulder.value, {font: '40px kenvector_future', fill: '#fff', align: 'center'}); }, /*reset: function() { this.zcar.x = 337; this.started = false; this.boul...
random_line_split
app.js
= { x: 0, y: 0 }; var imageX = 50; var imageY = 50; var tableGlobal; // var numXscale = canvas.clientWidth / canvas.width; // var numYscale = canvas.clientHeight / canvas.height; var imageWidth, imageHeight, imageRight, imageBottom; var draggingImage = false; var startX; var startY; // var img = new Image()...
function handleMouseOut(e) { if (!flagPin) { handleMouseUp(e); } } function handleMouseMove(e) { if (!flagPin) { if (draggingResizer > -1) { mouseX = parseInt(e.clientX - document.getElementById('canvas').offsetLeft)*canvas.width/canvas.clientWidth; mouseY = pars...
{ if (!flagPin) { draggingResizer = -1; draggingImage = false; draw(true, false); } }
identifier_body
app.js
= { x: 0, y: 0 }; var imageX = 50; var imageY = 50; var tableGlobal; // var numXscale = canvas.clientWidth / canvas.width; // var numYscale = canvas.clientHeight / canvas.height; var imageWidth, imageHeight, imageRight, imageBottom; var draggingImage = false; var startX; var startY; // var img = new Image()...
// bottom-left dx = x - canvas2realX(imageX); dy = y - canvas2realY(imageBottom); if (dx * dx + dy * dy <= rr) { return (3); } return (-1); } function hitImage(x, y) { return (x > canvas2realX(imageX) && x < canvas2realX(imageX + imageWidth) && y > canvas2realY(imageY) && y < canva...
{ return (2); }
conditional_block
app.js
izer = { x: 0, y: 0 }; var imageX = 50; var imageY = 50; var tableGlobal; // var numXscale = canvas.clientWidth / canvas.width; // var numYscale = canvas.clientHeight / canvas.height; var imageWidth, imageHeight, imageRight, imageBottom; var draggingImage = false; var startX; var startY; // var img = new Ima...
}; reader.readAsDataURL(file); } } evt.preventDefault(); }, false); updateAxis(); addTable(); function togglePin() { if (flagPin) { document.getElementById('idButtonPin').innerHTML = 'Start pinning'; flagPin = false; } else { document.getElementB...
random_line_split
app.js
= { x: 0, y: 0 }; var imageX = 50; var imageY = 50; var tableGlobal; // var numXscale = canvas.clientWidth / canvas.width; // var numYscale = canvas.clientHeight / canvas.height; var imageWidth, imageHeight, imageRight, imageBottom; var draggingImage = false; var startX; var startY; // var img = new Image()...
(withAnchors, withBorders) { // clear the canvas ctx.clearRect(0, 0, canvas.width, canvas.height); updateAxis(); // draw the image ctx.globalAlpha = 0.4; ctx.drawImage(imagDrop, 0, 0, imagDrop.width, imagDrop.height, imageX, imageY, imageWidth, imageHeight); // optionally draw the dragga...
draw
identifier_name
Z_normal_8_2.py
1.15]), 9: np.array([ -1.22, -0.76, -0.43, -0.14, 0.14, 0.43, 0.76, 1.22]), 10: np.array([ -1.28, -0.84, -0.52, -0.25, 0, 0.25, 0.52, 0.84, 1.28]), 11: np.array([ -1.34, -0.91, -0.6, -0.35, -0.11, 0.11, 0.35, 0.6, 0.91, 1.34]), 12: np.array([ -1.38, -0.97, -0.67, -0.4...
num+=chunk_size words.append(zlp) indices.append(curr_count) curr_count=curr_count+skip_offset-1 temp_list=[] temp_list.append(sub_section) temp_df = pd.DataFrame(temp_list) temp_df.insert(loc=0, column='keys', value=zlp) temp...
for j in range(0,word_lenth): chunk = sub_section[num:num + chunk_size] curr_word=alphabetize_ts(chunk) zlp+=str(curr_word) complete_indices.append(curr_count)
random_line_split
Z_normal_8_2.py
1.15]), 9: np.array([ -1.22, -0.76, -0.43, -0.14, 0.14, 0.43, 0.76, 1.22]), 10: np.array([ -1.28, -0.84, -0.52, -0.25, 0, 0.25, 0.52, 0.84, 1.28]), 11: np.array([ -1.34, -0.91, -0.6, -0.35, -0.11, 0.11, 0.35, 0.6, 0.91, 1.34]), 12: np.array([ -1.38, -0.97, -0.67, -0.4...
else: raise ValueError('A wrong idx value supplied.') def normalize(x): X = np.asanyarray(x) if np.nanstd(X) < epsilon: res = [] for entry in X: if not np.isnan(entry): res.append(0) else: ...
return chr(97 + idx)
conditional_block