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
main.rs
} fn mul_sub(x: Self, y: Self, z: Self) -> Self { Self(unsafe { _mm256_fmsub_ps(x.0, y.0, z.0) }) } } impl Add for WideF32 { type Output = Self; fn add(self, other: Self) -> Self { Self(unsafe { _mm256_add_ps(self.0, other.0) }) } } impl AddAssign for WideF32 { fn add_assign...
} impl Div for WideF32 { type Output = Self; fn div(self, other: Self) -> Self { Self(unsafe { _mm256_div_ps(self.0, other.0) }) } } impl Sub for WideF32 { type Output = Self; fn sub(self, other: Self) -> Self { Self(unsafe { _mm256_sub_ps(self.0, other.0) }) } } impl Mul f...
{ Self(unsafe { _mm256_or_ps(self.0, other.0) }) }
identifier_body
main.rs
} fn mul_sub(x: Self, y: Self, z: Self) -> Self { Self(unsafe { _mm256_fmsub_ps(x.0, y.0, z.0) }) } } impl Add for WideF32 { type Output = Self; fn add(self, other: Self) -> Self { Self(unsafe { _mm256_add_ps(self.0, other.0) }) } } impl AddAssign for WideF32 { fn add_assign...
{ xs: Vec<f32>, ys: Vec<f32>, zs: Vec<f32>, rsqrds: Vec<f32>, mats: Vec<Material>, } impl Spheres { fn new(spheres: Vec<Sphere>) -> Self { let len = (spheres.len() + SIMD_WIDTH - 1) / SIMD_WIDTH * SIMD_WIDTH; let mut me = Self { xs: Vec::with_capacity(len), ...
Spheres
identifier_name
main.rs
unsafe { _mm256_movemask_ps(self.0) } } fn hmin(&self) -> f32 { unsafe { /* This can be done entirely in avx with permute2f128, but that is allegedly very slow on AMD prior to Zen2 (and is anecdotally slower on my Intels as well) initial m256 ...
self.mask() != 0 } fn mask(&self) -> i32 {
random_line_split
CLCDcurve.py
1)) masstot = mass + passmass + fuelblock Weight_CL = [(masstot - FU_CL[i])*g for i in range(len(FU_CL))] CLgraph_mat = Weight_CL/(0.5 * VTAS_CL**2 * rho1_CL * S) print(min(Mach_CL), max(Mach_CL)) #find linear relation for CL measurements clalpha_mat,ma_mat = np.polyfit(AOA_CL[:,0],CLgraph_mat[:,0],1) CLline_CL = cla...
#Plots CL and CD## # plt.grid() # plt.scatter(AOA_CL,CLgraph_mat,marker= '.', label='Measure point') # # plt.plot(AOAstat,linecl_stat, label='Stationary Flight Measurements') # plt.plot(AOA_CL[:,0],CLline_CL,c='darkorange', label= 'Least Squares of Flightdata') # plt.ylabel('Lift Coefficient [-]') # plt.xlabel('Angle o...
CDstat = CD0 + linecl_stat/(pi * A * e)
random_line_split
mod.rs
step). Ok(self.iterate(heap)?.iter().collect()) } /// Produce an iterable from a value. pub fn iterate(self, heap: &'v Heap) -> anyhow::Result<RefIterable<'v>> { let me: ARef<'v, dyn StarlarkValue> = self.get_aref(); me.iterate()?; Ok(RefIterable::new( heap, ...
{ self.get_aref().get_type_value() }
identifier_body
mod.rs
fn collect_repr(self, collector: &mut String) { self.get_aref().collect_repr(collector); } fn to_json(self) -> anyhow::Result<String> { self.get_aref().to_json() } fn equals(self, other: Value<'v>) -> anyhow::Result<bool> { if self.to_value().ptr_eq(other) { Ok(...
export_as
identifier_name
mod.rs
for FrozenValue { fn eq(&self, other: &FrozenValue) -> bool { let v: Value = Value::new_frozen(*self); let other: Value = Value::new_frozen(*other); v.equals(other).ok() == Some(true) } } impl Eq for Value<'_> {} impl Eq for FrozenValue {} impl Equivalent<FrozenValue> for Value<'_> {...
} fn compare(self, other: Value<'v>) -> anyhow::Result<Ordering> { let _guard = stack_guard::stack_guard()?; self.get_aref().compare(other) } fn downcast_ref<T: AnyLifetime<'v>>(self) -> Option<ARef<'v, T>> { let any = ARef::map(self.get_aref(), |e| e.as_dyn_any()); if...
{ let _guard = stack_guard::stack_guard()?; self.get_aref().equals(other) }
conditional_block
mod.rs
} } impl Debug for FrozenValue { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { debug_value("FrozenValue", Value::new_frozen(*self), f) } } impl<'v> PartialEq for Value<'v> { fn eq(&self, other: &Value<'v>) -> bool { self.equals(*other).ok() == Some(true) } } impl PartialE...
debug_value("Value", *self, f)
random_line_split
encode.go
) encoderFunc { if fi, ok := encoderCache.Load(t); ok { return fi.(encoderFunc) } var ( wg sync.WaitGroup f encoderFunc ) wg.Add(1) fi, loaded := encoderCache.LoadOrStore(t, encoderFunc(func(e *encodeState, v reflect.Value) { wg.Wait() f(e, v) })) if loaded { return fi.(encoderFunc) } f = newTy...
random_line_split
encode.go
return invalidValueEncoder } return typeEncoder(v.Type()) } func typeEncoder(t reflect.Type) encoderFunc { if fi, ok := encoderCache.Load(t); ok { return fi.(encoderFunc) } var ( wg sync.WaitGroup f encoderFunc ) wg.Add(1) fi, loaded := encoderCache.LoadOrStore(t, encoderFunc(func(e *encodeState, v r...
(t reflect.Type, index []int) reflect.Type { for _, i := range index { if t.Kind() == reflect.Ptr { t = t.Elem() } t = t.Field(i).Type } return t } type field struct { name string tags map[string]string index []int typ reflect.Type } // byIndex sorts field by index sequence. type byIndex []field ...
typeByIndex
identifier_name
encode.go
return e.Bytes(), nil } // Marshaler is the interface implemented by types that can marshal // themselves into valid BNET. type Marshaler interface { MarshalBNet() ([]byte, error) } // An UnsupportedTypeError occurs when attempting to marshal an // unsupported type. type UnsupportedTypeError struct { Type reflect...
{ return nil, err }
conditional_block
encode.go
return invalidValueEncoder } return typeEncoder(v.Type()) } func typeEncoder(t reflect.Type) encoderFunc { if fi, ok := encoderCache.Load(t); ok { return fi.(encoderFunc) } var ( wg sync.WaitGroup f encoderFunc ) wg.Add(1) fi, loaded := encoderCache.LoadOrStore(t, encoderFunc(func(e *encodeState, v r...
func encodeStringSlice(e *encodeState, v reflect.Value) { n := v.Len() for i := 0; i < n; i++ { stringEncoder(e, v.Index(i)) } e.buf.WriteByte(0x00) } type sliceEncoder struct { arrayEnc encoderFunc } func (se *sliceEncoder) encode(e *encodeState, v reflect.Value) { if v.IsNil() { return } se.arrayEnc(e...
{ fields := cachedTypeFields(t) se := &structEncoder{ fields: fields, fieldEncs: make([]encoderFunc, len(fields)), } for i, f := range fields { se.fieldEncs[i] = typeEncoder(typeByIndex(t, f.index)) } return se.encode }
identifier_body
backend.rs
Box<dyn TargetIsa>, symbols: HashMap<String, *const u8>, libcall_names: Box<dyn Fn(ir::LibCall) -> String>, code_memory: Memory, readonly_memory: Memory, writable_memory: Memory, } /// A record of a relocation to perform. struct RelocRecord { offset: CodeOffset, reloc: Reloc, name: ir:...
get_finalized_function
identifier_name
backend.rs
.code, None => self.lookup_symbol(name_str), } } else { let (def, name_str, _writable) = namespace.get_data_definition(&name); match def { Some(compiled) => compiled.storage, ...
| Reloc::X86CallPCRel4
random_line_split
backend.rs
{ debug_assert!(!isa.flags().is_pic(), "SimpleJIT requires non-PIC code"); let symbols = HashMap::new(); Self { isa, symbols, libcall_names, } } /// Define a symbol in the internal symbol table. /// /// The JIT will use the symbol tab...
fn declare_function(&mut self, _name: &str, _linkage: Linkage) { // Nothing to do. } fn declare_data( &mut self, _name: &str, _linkage: Linkage, _writable: bool, _align: Option<u8>, ) { // Nothing to do. } fn define_function( &m...
{ &*self.isa }
identifier_body
composition_patches.go
// Default PatchTypePatchSet PatchType = "PatchSet" PatchTypeToCompositeFieldPath PatchType = "ToCompositeFieldPath" PatchTypeCombineFromComposite PatchType = "CombineFromComposite" PatchTypeCombineToComposite PatchType = "CombineToComposite" ) // A FromFieldPathPolicy determines how to patc...
// patchFieldValueToObject, given a path, value and "to" object, will // apply the value to the "to" object at the given path, returning // any errors as they occur. func patchFieldValueToObject(fieldPath string, value interface{}, to runtime.Object, mo *xpv1.MergeOptions) error { paved, err := fieldpath.PaveObject(...
{ var err error for i, t := range c.Transforms { if input, err = t.Transform(input); err != nil { return nil, errors.Wrapf(err, errFmtTransformAtIndex, i) } } return input, nil }
identifier_body
composition_patches.go
Type) error { if c.filterPatch(only...) { return nil } switch c.Type { case PatchTypeFromCompositeFieldPath: return c.applyFromFieldPathPatch(cp, cd) case PatchTypeToCompositeFieldPath: return c.applyFromFieldPathPatch(cd, cp) case PatchTypeCombineFromComposite: return c.applyCombineFromVariablesPatch(cp...
} if p.PatchSetName == nil {
random_line_split
composition_patches.go
// Default PatchTypePatchSet PatchType = "PatchSet" PatchTypeToCompositeFieldPath PatchType = "ToCompositeFieldPath" PatchTypeCombineFromComposite PatchType = "CombineFromComposite" PatchTypeCombineToComposite PatchType = "CombineToComposite" ) // A FromFieldPathPolicy determines how to patc...
switch c.Type { case PatchTypeFromCompositeFieldPath: return c.applyFromFieldPathPatch(cp, cd) case PatchTypeToCompositeFieldPath: return c.applyFromFieldPathPatch(cd, cp) case PatchTypeCombineFromComposite: return c.applyCombineFromVariablesPatch(cp, cd) case PatchTypeCombineToComposite: return c.applyC...
{ return nil }
conditional_block
composition_patches.go
PatchSet;ToCompositeFieldPath;CombineFromComposite;CombineToComposite // +kubebuilder:default=FromCompositeFieldPath Type PatchType `json:"type,omitempty"` // FromFieldPath is the path of the field on the resource whose value is // to be used as input. Required when type is FromCompositeFieldPath or // ToComposit...
Combine
identifier_name
Training.py
경로 TRAIN_CSV = "train_shuffle.csv" # train data .csv VALIDATION_CSV = "validation_shuffle.csv" # validation data .csv TEST_CSV = "test_uniform.csv" # test data .csv MODEL_SAVE_FOLDER_PATH = './model/' # 저장될 모델 디렉토리 설정 class DataGenerator(Sequence): def __init__(self, csv_file): self.paths = [] ...
poch, logs): train_pos_count = 0 train_neg_count = 0 for i in range(len(self.generator)): batch_images, gt = self.generator[i] pred = self.model.predict_on_batch(batch_images) train_gt_len = len(gt) pred = np.maximum(pred, 0) ########...
def on_epoch_end(self, e
identifier_body
Training.py
validation 경로 TRAIN_CSV = "train_shuffle.csv" # train data .csv VALIDATION_CSV = "validation_shuffle.csv" # validation data .csv TEST_CSV = "test_uniform.csv" # test data .csv MODEL_SAVE_FOLDER_PATH = './model/' # 저장될 모델 디렉토리 설정 class DataGenerator(Sequence): def __init__(self, csv_file): self.paths ...
class Test_set(Callback): def __init__(self, generator): self.generator = generator def on_epoch_end(self, epoch, logs): test_pos_count = 0 test_neg_count = 0 for i in range(len(self.generator)): batch_images, gt = self.generator[i] pred = self.model.p...
mse = np.round(mse, 4) logs["val_mse"] = mse print(" - val_iou: {} - val_mse: {} - val_acc: {}".format(iou, mse, val_acc))
random_line_split
Training.py
validation 경로 TRAIN_CSV = "train_shuffle.csv" # train data .csv VALIDATION_CSV = "validation_shuffle.csv" # validation data .csv TEST_CSV = "test_uniform.csv" # test data .csv MODEL_SAVE_FOLDER_PATH = './model/' # 저장될 모델 디렉토리 설정 class DataGenerator(Sequence): def __init__(self, csv_file): self.paths ...
intersections = 0 unions = 0 val_pos_count = 0 val_neg_count = 0 for i in range(len(self.generator)): batch_images, gt = self.generator[i] pred = self.model.predict_on_batch(batch_images) mse += np.linalg.norm(gt - pred, ord='fro') / pred.shape[0] ...
= 0
identifier_name
Training.py
경로 TRAIN_CSV = "train_shuffle.csv" # train data .csv VALIDATION_CSV = "validation_shuffle.csv" # validation data .csv TEST_CSV = "test_uniform.csv" # test data .csv MODEL_SAVE_FOLDER_PATH = './model/' # 저장될 모델 디렉토리 설정 class DataGenerator(Sequence): def __init__(self, csv_file): self.paths = [] ...
train_총 갯수 train_acc = np.round(train_pos_count / train_data_count, 4) logs["train_acc"] = train_acc print(" - train_acc: {}".format(train_acc)) class Validation(Callback): def __init__(self, generator): self.generator = generator def on_epoch_end(self, epoch, logs): ...
shold 0.5 지정 train_pos_count += 1 else: train_neg_count += 1 train_data_count = 59521 #
conditional_block
models.py
'Spanish'), ('Swedish', 'Swedish'), ('Tamil', 'Tamil'), ('Telugu', 'Telugu'), ('Turkish', 'Turkish'), ('Ukrainian', 'Ukrainian'), ('Urdu', 'Urdu'), ('Vietnamese', 'Vietnamese') ) CITIES = ( ('Abidjan', 'Abidjan'), ('Accra', 'Accra'), ('Addis Ababa', 'Addis Ababa'), ('Ahmedabad', 'Ahmedabad'), ...
('Incheon', 'Incheon'), ('Indianapolis', 'Indianapolis'), ('Irvine', 'Irvine'), ('Irving', 'Irving'), ('Istanbul', 'Istanbul'), ('İzmir', 'İzmir'), ('Jacksonville', 'Jacksonville'), ('Jaipur', 'Jaipur'), ('Jakarta', 'Jakarta'), ('Jeddah', 'Jeddah'), ('Jersey City', 'Jersey Ci...
('Ibadan', 'Ibadan'),
random_line_split
models.py
'Hong Kong'), ('Honolulu', 'Honolulu'), ('Houston', 'Houston'), ('Hyderabad', 'Hyderabad'), ('Ibadan', 'Ibadan'), ('Incheon', 'Incheon'), ('Indianapolis', 'Indianapolis'), ('Irvine', 'Irvine'), ('Irving', 'Irving'), ('Istanbul', 'Istanbul'), ('İzmir', 'İzmir'), ('Jacksonvill...
: return
identifier_name
models.py
'), ('Hyderabad', 'Hyderabad'), ('Ibadan', 'Ibadan'), ('Incheon', 'Incheon'), ('Indianapolis', 'Indianapolis'), ('Irvine', 'Irvine'), ('Irving', 'Irving'), ('Istanbul', 'Istanbul'), ('İzmir', 'İzmir'), ('Jacksonville', 'Jacksonville'), ('Jaipur', 'Jaipur'), ('Jakarta', 'Jakar...
tail', kwargs = { 'pk': self.id }) # ---- BOOKING ----
identifier_body
github.go
", orgThrottler)) continue } if burst > hourlyTokens { errs = append(errs, fmt.Errorf("-github-throttle-org=%s: burst must not be greater than hourlyTokens", orgThrottler)) continue } if _, alreadyExists := o.parsedOrgThrottlers[org]; alreadyExists { errs = append(errs, fmt.Errorf("got multiple -git...
{ if _, err := o.GitHubClient(dryRun); err != nil { return "", nil, fmt.Errorf("error getting GitHub client: %w", err) } }
conditional_block
github.go
(hourlyTokens, allowedBursts int) FlagParameter { return func(o *flagParams) { o.defaults.ThrottleHourlyTokens = hourlyTokens o.defaults.ThrottleAllowBurst = allowedBursts } } // DisableThrottlerOptions suppresses the presence of throttler-related flags, // effectively disallowing external users to parametrize d...
ThrottlerDefaults
identifier_name
github.go
!= 3 { errs = append(errs, fmt.Errorf("-github-throttle-org=%s is not in org:hourlyTokens:burst format", orgThrottler)) continue } org, hourlyTokensString, burstString := colonSplit[0], colonSplit[1], colonSplit[2] hourlyTokens, err := strconv.ParseInt(hourlyTokensString, 10, 32) if err != nil { errs ...
{ var gitClientFactory gitv2.ClientFactory if cookieFilePath != "" && o.TokenPath == "" && o.AppPrivateKeyPath == "" { opts := gitv2.ClientFactoryOpts{ CookieFilePath: cookieFilePath, Persist: &persistCache, } if cacheDir != nil && *cacheDir != "" { opts.CacheDirBase = cacheDir } var err err...
identifier_body
github.go
options. Note that validate updates the GitHubOptions // to add default values for TokenPath and graphqlEndpoint. func (o *GitHubOptions) Validate(bool) error { endpoints := o.endpoint.Strings() for i, uri := range endpoints { if uri == "" { endpoints[i] = github.DefaultAPIEndpoint } else if _, err := url.Par...
},
random_line_split
token.rs
Helper counter for testing to diagnose /// how many rollbacks have occured pub rollbacks: u64, } impl Ledger { /// Helper method to get the account details for `owner_id`. fn get_balance(&self, owner_id: &AccountId) -> u128 { match self.balances.get(owner_id) { Some(x) => return ...
//// How many rollbacks we have had pub fn get_rollback_count(&self) -> u64 { self.ledger.rollbacks } /// Returns balance of the `owner_id` account. pub fn get_name(&self) -> &str { return &self.metadata.name; } /// Send owner's tokens to another person or a smart contrac...
{ self.ledger.get_locked_balance(&owner_id).into() }
identifier_body
token.rs
) -> Balance { match self.locked_balances.get(owner_id) { Some(x) => return x, None => return 0, } } /** * Send tokens to a new owner. * * message is an optional byte data that is passed to the receiving smart contract. * notify is a flag to tell if w...
{ // The send() was destined to a compatible receiver smart contract. // Build another promise that notifies the smart contract // that is has received new tokens. env::log(b"Constructing smart contract notifier promise"); let promise0 = env::promise_create...
conditional_block
token.rs
&[], 0, SINGLE_CALL_GAS/3, ); let promise1 = env::promise_then( promise0, env::current_account_id(), b"handle_receiver", json!({ "old_owner_id": owner_id, "new_owner_id": new_owner_id, ...
block_index: 0, block_timestamp: 0,
random_line_split
token.rs
(&new_owner_id); let new_target_balance = target_balance + amount; self.set_balance(&new_owner_id, new_target_balance); // This much of user balance is lockedup in promise chains self.set_balance(&new_owner_id, new_target_balance); let target_lock = self.get_locked_balance(&new...
bob
identifier_name
mp4-tools.ts
{ let matchingTraf = trafs[index]; mdatTrafPairs.push({ mdat: mdat, traf: matchingTraf }); }); mdatTrafPairs.forEach(function (pair) { let mdat = pair.mdat; let mdatBytes = mdat.data.subarray(mdat.start, mdat.end); let traf = pair.traf; let trafBytes = traf.data.subarray(tr...
{ logger.log('We\'ve encountered a nal unit without data. See mux.js#233.'); break; }
conditional_block
mp4-tools.ts
= mdat.data.subarray(mdat.start, mdat.end); let traf = pair.traf; let trafBytes = traf.data.subarray(traf.start, traf.end); let tfhd = findBox(trafBytes, ['tfhd']); // Exactly 1 tfhd per traf let headerInfo = parseTfhd(tfhd[0]); let trackId = headerInfo.trackId; let tfdt = findBox(trafBytes...
parseTrun
identifier_name
mp4-tools.ts
5, Section 8.1.1 * @see Rec. ITU-T H.264, 7.3.2.3.1 **/ export function findSeiNals (avcStream, samples, trackId) { let avcView = new DataView(avcStream.buffer, avcStream.byteOffset, avcStream.byteLength), result = [] as any, seiNal, i, length, lastMatchedSample; for (i = 0; i + 4 < avc...
{ let trafs, baseTimes, result; // we need info from two childrend of each track fragment box trafs = findBox(fragment, ['moof', 'traf']); // determine the start times for each track baseTimes = [].concat.apply([], trafs.map(function (traf) { return findBox(traf, ['tfhd']).map(function (tfhd) { le...
identifier_body
mp4-tools.ts
Object[]>} A mapping of video trackId to * a list of seiNals found in that track **/ export function parseCaptionNals (data, videoTrackId) { let captionNals = [] as any; // To get the samples let trafs = findBox(data, ['moof', 'traf']); // To get SEI NAL units let mdats = findBox(data, ['mdat']); let...
escapedRBSP: discardEmulationPreventionBytes(data), trackId: trackId };
random_line_split
processor.rs
system, such as "Windows NT", "Mac OS X", or "Linux". /// /// If the information is present in the dump but its value is unknown, this field will contain /// a numeric value. If the information is not present in the dump, this field will be empty. pub fn os_name(&self) -> String { unsafe { ...
{ Ok(ProcessState { internal, _ty: PhantomData, }) }
conditional_block
processor.rs
/// Returns the `CodeModule` that contains this frame's instruction. pub fn module(&self) -> Option<&CodeModule> { unsafe { stack_frame_module(self).as_ref() } } /// Returns how well the instruction pointer is trusted. pub fn trust(&self) -> FrameTrust { unsafe { stack_frame_trust(s...
ProcessState
identifier_name
processor.rs
instruction of this stack frame. #[repr(C)] pub struct StackFrame(c_void); impl StackFrame { /// Returns the program counter location as an absolute virtual address. /// /// - For the innermost called frame in a stack, this will be an exact /// program counter or instruction pointer value. /// ...
/// The minidump file had no header.
random_line_split
level_2_optionals_cdsu.py
('Versão', 'trendl'): 'trendline', ('Versão', 'conft'): 'confortline', ('Versão', 'highlin'): 'highline', ('Versão', 'confortine'): 'confortline', ('Versão', 'cofrtl'): 'confortline', ('Versão', 'confortlline'): 'confortline', ('Versão', 'highl'): 'highline', ('Modelo', 'up!'): 'up'} ...
project_identifier, exception_desc = level_2_optionals_cdsu_options.project_id, str(sys.exc_info()[1]) log_record(exception_desc, project_identifier, flag=2) error_upload(level_2_optionals_cdsu_options, project_identifier, format_exc(), exception_desc, error_flag=1) log_record('Falhou - Projeto...
conditional_block
level_2_optionals_cdsu.py
is {}'.format(max(df['Sell_Date']))) return def data_processing(df): performance_info_append(time.time(), 'Section_B_Start') log_record('Início Secção B...', project_id) log_record('Checkpoint não encontrado ou demasiado antigo. A processar dados...', project_id) df = lowercase_column_conversi...
df = remove_columns(df, ['Cor', 'Interior', 'Opcional', 'Custo', 'Versão', 'Franchise_Code'], project_id) # Remove columns not needed atm; # Will probably need to also remove: stock_days, stock_days_norm, and one of the scores
random_line_split
level_2_optionals_cdsu.py
fortline', ('Versão', 'conftl'): 'confortline', ('Versão', 'hightline'): 'highline', ('Versão', 'bluem'): 'bluemotion', ('Versão', 'bmt'): 'bluemotion', ('Versão', 'up!bluemotion'): 'up! bluemotion', ('Versão', 'up!bluem'): 'up! bluemotion', ('Versão', 'trendl'): 'trendline', ('Versão', '...
log_record('Início Secção E...', project_id) if df is not None: df['NLR_Code'] = level_2_optionals_cdsu_options.nlr_code # df = column_rename(df, list(level_2_optionals_cdsu_options.column_sql_renaming.keys()), list(level_2_optionals_cdsu_options.column_sql_renaming.values())) df = df.re...
identifier_body
level_2_optionals_cdsu.py
uery_filters): performance_info_append(time.time(), 'Section_A_Start') log_record('Início Secção A...', project_id) df = sql_retrieve_df(level_2_optionals_cdsu_options.DSN_MLG_PRD, level_2_optionals_cdsu_options.sql_info['database'], level_2_optionals_cdsu_options.sql_info['initial_table'], level_2_optiona...
ta_acquisition(q
identifier_name
util.js
var a = "", b = this.indexOf(e); if (b != -1) { b += e.length; var d = this.indexOf(c, b); if (d != -1) { a = this.substr(b, d - b) } } return a }; StringUtils.capitalize = function(e, c) { e = StringUtils.trimLeft(e); return c === true ? e.replace(/^.|\s+(.)/, StringUtils._upperCa...
} return this.substr(0, e) }; String.prototype.between = function(e, c) {
random_line_split
util.js
if (c == null) { c = " " } var a = c.substr(0, 1); return this.length < e ? this + this.repeat(e - this.length, a) : this }; String.prototype.rjust = function(e, c) { if (c == null) { c = " " } var a = c.substr(0, 1); return this.length < e ? this.repeat(e - this.length, a) + this : this }; Strin...
for (m = 0; m <= g; m++) { a[0][m] = m } for (m = 1; m <= d; m++) { for (var q = e.charAt(m - 1), s = 1; s <= g; s++) { b = c.charAt(s - 1); b = q == b ? 0 : 1; a[m][s] = Math.min(a[m - 1][s] + 1, a[m][s - 1] + 1, a[m - 1][s - 1] + b) } } return a[d][g] }; String.prototype.editD...
{ a[m][0] = m }
conditional_block
util.js
] = [] } for (m = 0; m <= d; m++) { a[m][0] = m } for (m = 0; m <= g; m++) { a[0][m] = m } for (m = 1; m <= d; m++) { for (var q = e.charAt(m - 1), s = 1; s <= g; s++) { b = c.charAt(s - 1); b = q == b ? 0 : 1; a[m][s] = Math.min(a[m - 1][s] + 1, a[m][s - 1] + 1, a[m - 1][s - 1...
{ return (new Date).getTime() }
identifier_body
util.js
if (c == null) { c = " " } var a = c.substr(0, 1); return this.length < e ? this + this.repeat(e - this.length, a) : this }; String.prototype.rjust = function(e, c) { if (c == null) { c = " " } var a = c.substr(0, 1); return this.length < e ? this.repeat(e - this.length, a) + this : this }; Stri...
() { throw Error("Rnd is static and cannot be instantiated."); } Rnd.randFloat = function(e, c) { if (isNaN(c)) { c = e; e = 0 } return Math.random() * (c - e) + e }; Rnd.randBoolean = function(e) { if (isNaN(e)) { e = 0.5 } return Math.random() < e }; Rnd.randSign = function(e) { if (isNaN(...
Rnd
identifier_name
img-touch-clip.js
.path; //从canvas-zoom迁移过来,关于边框等元素的adaption的设置 this.scaleAdaption = 1; var indoormap =options.canvas; var pageWidth = parseInt(indoormap.getAttribute("width")); //750 var pageHeight = parseInt(indoormap.getAttribute("height"));//1180 currentWidth = document.documentEle...
_img_sx:0, _img_sy:0, // 图片的高宽 _imgW:0, _imgH:0, init_url: function(url){ this.imgTexture = new Image(); this.imgTexture.src=url; this.init=false; this.box_Scale=1; this.position = { x: 0, ...
// _img:this.imgTexture, //剪裁的x y坐标
random_line_split
IIoT End-to-End (Pt 2).py
.secrets.get("iot","adls_key")) # Setup storage locations for all data ROOT_PATH = f"abfss://iot@{storage_account}.dfs.core.windows.net/" # Pyspark and ML Imports import os, json, requests from pyspark.sql import functions as F from pyspark.sql.functions import pandas_udf, PandasUDFType import numpy as np import pan...
(readings_pd): return train_distributed_xgb(readings_pd, 'power_prediction', label_col, prediction_col) # Run the Pandas UDF against our feature dataset - this will train 1 model for each turbine power_predictions = feature_df.groupBy('deviceid').apply(train_power_models) # Save predictions to storage power_predict...
train_power_models
identifier_name
IIoT End-to-End (Pt 2).py
gboost import mlflow.azureml from azureml.core import Workspace from azureml.core.webservice import AciWebservice, Webservice import random, string # Random String generator for ML models served in AzureML random_string = lambda length: ''.join(random.SystemRandom().choice(string.ascii_lowercase) for _ in range(length...
return train_distributed_xgb(readings_pd, 'life_prediction', label_col, prediction_col)
identifier_body
IIoT End-to-End (Pt 2).py
# MAGIC [Pandas UDFs](https://docs.microsoft.com/en-us/azure/databricks/spark/latest/spark-sql/udf-python-pandas?toc=https%3A%2F%2Fdocs.microsoft.com%2Fen-us%2Fazure%2Fazure-databricks%2Ftoc.json&bc=https%3A%2F%2Fdocs.microsoft.com%2Fen-us%2Fazure%2Fbread%2Ftoc.json) allow us to vectorize Pandas code across multiple no...
print(f"-----Building image for {model} model-----") model_image, azure_model = mlflow.azureml.build_image(model_uri=path, workspace=workspace, model_name=model, ...
conditional_block
IIoT End-to-End (Pt 2).py
utils.secrets.get("iot","adls_key")) # Setup storage locations for all data ROOT_PATH = f"abfss://iot@{storage_account}.dfs.core.windows.net/" # Pyspark and ML Imports import os, json, requests from pyspark.sql import functions as F from pyspark.sql.functions import pandas_udf, PandasUDFType import numpy as np impor...
# MAGIC %md #### Automated Model Tracking in Databricks # MAGIC As you train the models, notice how Databricks-managed MLflow automatically tracks each run in the "Runs" tab of the notebook. You can open each run and view the parameters, metrics, models and model artifacts that are captured by MLflow Autologging. For X...
# MAGIC -- Plot actuals vs. predicted # MAGIC SELECT date, deviceid, avg(power_6_hours_ahead) as actual, avg(power_6_hours_ahead_predicted) as predicted FROM turbine_power_predictions GROUP BY date, deviceid # COMMAND ----------
random_line_split
builders.rs
b| b /// .merge(serde_json::from_str(r#"{"name":"My Server"}"#)?)) /// ``` pub fn merge(mut self, other: $name) -> $name { self.0.extend(other.0); self } } )* } } builder! { /// Patch content for the `edit_server` call. EditServer(Object); /// Patch content for the `edit_channel` cal...
(self, bitrate: u64) -> Self { set!(self, "bitrate", bitrate) } /// Edit the voice channel's user limit. Zero (`0`) means unlimited. pub fn user_limit(self, user_limit: u64) -> Self { set!(self, "user_limit", user_limit) } } impl EditMember { /// Edit the member's nickname. Supply the empty string to remove ...
bitrate
identifier_name
builders.rs
#[inline(always)] pub fn __build<F: FnOnce($name) -> $name>(f: F) -> $inner where $inner: Default { Self::__apply(f, Default::default()) } #[doc(hidden)] pub fn __apply<F: FnOnce($name) -> $name>(f: F, inp: $inner) -> $inner { f($name(inp)).0 } /// Merge this builder's contents w...
impl $name { #[doc(hidden)]
random_line_split
builders.rs
b| b /// .merge(serde_json::from_str(r#"{"name":"My Server"}"#)?)) /// ``` pub fn merge(mut self, other: $name) -> $name { self.0.extend(other.0); self } } )* } } builder! { /// Patch content for the `edit_server` call. EditServer(Object); /// Patch content for the `edit_channel` cal...
/// Transfer ownership of the server to a new owner. pub fn owner(self, owner: UserId) -> Self { set!(self, "owner_id", owner.0) } /// Edit the verification level of the server. pub fn verification_level(self, verification_level: VerificationLevel) -> Self { set!(self, "verification_level", verification_lev...
{ set!(self, "afk_timeout", timeout) }
identifier_body
philo2.go
maxDinner int currentlyEating int tableCount int chopsticksFree []bool freeSeats []int } // philosopherData contains philosopher specific data. It is used within DinnerHost. type philosopherData struct { respChannel chan string eating bool dinnersSpent int seat int le...
(name string) string { if host.currentlyEating >= host.maxParallel { return "E:FULL" } data := host.phiData[name] canEat := data.CanEat(host.maxDinner) if canEat != "OK" { return canEat } seatNumber := data.Seat() leftChop := seatNumber rightChop := (seatNumber + 1) % host.tableCount if host.chopstick...
AllowEating
identifier_name
philo2.go
maxDinner int currentlyEating int tableCount int chopsticksFree []bool freeSeats []int } // philosopherData contains philosopher specific data. It is used within DinnerHost. type philosopherData struct { respChannel chan string eating bool dinnersSpent int seat int le...
host.chopsticksFree[host.phiData[name].LeftChopstick()] = true host.chopsticksFree[host.phiData[name].RightChopstick()] = true host.phiData[name].FinishedEating() fmt.Println(name + " FINISHED EATING.") fmt.Println() } // PrintReport shows the status of the philosophers in a verbose format. func (host *DinnerHos...
{ host.currentlyEating-- }
conditional_block
philo2.go
The host of the dinner. --- */ // DinnerHost is the main data structure for the host of the dinner. type DinnerHost struct { phiData map[string]*philosopherData requestChannel chan string finishChannel chan string maxParallel int maxDinner int currentlyEating int tableCount int chopst...
/* ---
random_line_split
philo2.go
Count } host.maxDinner = maxDinner host.currentlyEating = 0 host.tableCount = tableCount host.chopsticksFree = make([]bool, 5) for i := range host.chopsticksFree { host.chopsticksFree[i] = true } rand.Seed(time.Now().Unix()) host.freeSeats = rand.Perm(tableCount) } // newPhilosopherDataPtr creates and initi...
{ return pd.rightChopstick }
identifier_body
verify_cert.rs
cert: &Cert, time: time::Time, sub_ca_count: usize, ) -> Result<(), Error> { let used_as_ca = used_as_ca(&cert.ee_or_ca); check_issuer_independent_properties( cert, time, used_as_ca, sub_ca_count, required_eku_if_present, )?; // TODO: HPKP checks. ...
( input: Option<&mut untrusted::Reader>, used_as_ca: UsedAsCa, sub_ca_count: usize, ) -> Result<(), Error> { let (is_ca, path_len_constraint) = match input { Some(input) => { let is_ca = der::optional_boolean(input)?; // https://bugzilla.mozilla.org/show_bug.cgi?id=98502...
check_basic_constraints
identifier_name
verify_cert.rs
cert: &Cert, time: time::Time, sub_ca_count: usize, ) -> Result<(), Error> { let used_as_ca = used_as_ca(&cert.ee_or_ca); check_issuer_independent_properties( cert, time, used_as_ca, sub_ca_count, required_eku_if_present, )?; // TODO: HPKP checks. ...
// https://tools.ietf.org/html/rfc5280#section-4.1.2.5 fn check_validity(input: &mut untrusted::Reader, time: time::Time) -> Result<(), Error> { let not_before = der::time_choice(input)?; let not_after = der::time_choice(input)?; if not_before > not_after { return Err(Error::InvalidCertValidity);...
{ // TODO: check_distrust(trust_anchor_subject, trust_anchor_spki)?; // TODO: Check signature algorithm like mozilla::pkix. // TODO: Check SPKI like mozilla::pkix. // TODO: check for active distrust like mozilla::pkix. // See the comment in `remember_extension` for why we don't check the // Key...
identifier_body
verify_cert.rs
cert: &Cert, time: time::Time, sub_ca_count: usize, ) -> Result<(), Error> { let used_as_ca = used_as_ca(&cert.ee_or_ca); check_issuer_independent_properties( cert, time, used_as_ca, sub_ca_count, required_eku_if_present, )?; // TODO: HPKP checks. ...
// * We follow the convention established by Microsoft's implementation and // mozilla::pkix
// Notable Differences from RFC 5280: //
random_line_split
move_vm.go
enabled clones to image service will not be deleted") fmt.Println("--delete Deletes source VM - ARE YOU REALLY SURE?") fmt.Println("--overwrite Overwrites target VM/Images (delete and creates new one)") fmt.Println("--help List this help") fmt.Println("--version Show the move_...
} func evaluateFlags() (ntnxAPI.NTNXConnection, ntnxAPI.VMJSONAHV, ntnxAPI.VMJSONAHV, []ntnxAPI.VMDisks) { //help if *help { printHelp() os.Exit(0) } //version if *version { fmt.Println("Version: " + appVersion) os.Exit(0) } //debug if *debug { log.SetLevel(log.DebugLevel) } else { log.SetLev...
{ defer func() { if err := recover(); err != nil { log.Fatal("--vdisk-mapping is not correct") os.Exit(1) } }() for i, elem := range v.Config.VMDisks { if elem.Addr.DeviceBus != VdiskMapping[i].Addr.DeviceBus || elem.Addr.DeviceIndex != VdiskMapping[i].Addr.DeviceIndex { log.Error("--vdisk-mapping s...
identifier_body
move_vm.go
enabled clones to image service will not be deleted") fmt.Println("--delete Deletes source VM - ARE YOU REALLY SURE?") fmt.Println("--overwrite Overwrites target VM/Images (delete and creates new one)") fmt.Println("--help List this help") fmt.Println("--version Show the move_...
return n, vm, vNew, VdiskMapping } func main() { flag.Usage = printHelp flag.Parse() customFormatter := new(log.TextFormatter) customFormatter.TimestampFormat = "2006-01-02 15:04:05" log.SetFormatter(customFormatter) customFormatter.FullTimestamp = true var n ntnxAPI.NTNXConnection var v ntnxAPI.VMJSONA...
{ VdiskMapping, err = parseVdiskMapping(&n) if err != nil { os.Exit(1) } }
conditional_block
move_vm.go
If enabled clones to image service will not be deleted") fmt.Println("--delete Deletes source VM - ARE YOU REALLY SURE?") fmt.Println("--overwrite Overwrites target VM/Images (delete and creates new one)") fmt.Println("--help List this help") fmt.Println("--version Show the mo...
(n *ntnxAPI.NTNXConnection) ([]ntnxAPI.VMDisks, error) { defer func() { if err := recover(); err != nil { log.Fatal("--vdisk-mapping seems not to have right format") os.Exit(1) } }() var vdiskMappings []ntnxAPI.VMDisks var VMDisk ntnxAPI.VMDisks result := strings.Split(*vdiskMapping, ",") // add Ma...
parseVdiskMapping
identifier_name
move_vm.go
If enabled clones to image service will not be deleted") fmt.Println("--delete Deletes source VM - ARE YOU REALLY SURE?") fmt.Println("--overwrite Overwrites target VM/Images (delete and creates new one)") fmt.Println("--help List this help") fmt.Println("--version Show the mo...
log.Error("--vdisk-mapping seems not to have right format") os.Exit(1) } if !(VMDisk.Addr.DeviceIndex >= 0 && VMDisk.Addr.DeviceIndex <= 255) { log.Error("--vdisk-mapping seems not to have right format") os.Exit(1) } if res[1] != "EMPTY" { containerUUID, err := ntnxAPI.GetContainerUUIDbyName(n,...
// check if right format is used if !(VMDisk.Addr.DeviceBus == "scsi" || VMDisk.Addr.DeviceBus == "pci" || VMDisk.Addr.DeviceBus == "ide") {
random_line_split
model.py
None: # empty model self.model = None self.keywords = None elif _type == "fixed": if pre_trained_model_json is None: raise RatingModel.RatingModel.Error("pre_trained_model_json is None") self.loadModelFixed(pre_trained_model_jso...
def __trainKMWM(self,seen_chunks_words: List[str],all_tokens_chunks: List[Any], keywords: List[str]) -> Optional[Tuple[List[float], List[float]]]: """ Hidden function to obtain KM and WM scores from keywords :param seen_chunks_words: n-grams of words in doc :param ...
return [word for word in text if word in self.top_k_words]
identifier_body
model.py
None: # empty model self.model = None self.keywords = None elif _type == "fixed": if pre_trained_model_json is None: raise RatingModel.RatingModel.Error("pre_trained_model_json is None") self.loadModelFixed(pre_trained_model_jso...
elif self._type == "lda": if self.lda is None or self.dictionary is None or self.top_k_words is None: raise RatingModel.RatingModelError("No LDA found") seen_chunks_words, all_tokens_chunks = getAllTokensAndChunks(doc) seen_chunks_words, all_tokens_chu...
print("working on fixed model") if self.keywords is None: raise RatingModel.RatingModelError("Keywords not found") seen_chunks_words, all_tokens_chunks = getAllTokensAndChunks(doc) # scoring temp_out = self.__trainKMWM(list(seen_chunks_words), lis...
conditional_block
model.py
None: # empty model self.model = None self.keywords = None elif _type == "fixed": if pre_trained_model_json is None: raise RatingModel.RatingModel.Error("pre_trained_model_json is None") self.loadModelFixed(pre_trained_model_jso...
elif self._type == "lda": if self.lda is None or self.dictionary is None or self.top_k_words is None: raise RatingModel.RatingModelError("No LDA found") seen_chunks_words, all_tokens_chunks = getAllTokensAndChunks(doc) seen_chunks_words, all_tokens_chunk...
final_score = km_score * wm_score
random_line_split
model.py
: # empty model self.model = None self.keywords = None elif _type == "fixed": if pre_trained_model_json is None: raise RatingModel.RatingModel.Error("pre_trained_model_json is None") self.loadModelFixed(pre_trained_model_json) ...
(self,seen_chunks_words: List[str],all_tokens_chunks: List[Any], keywords: List[str]) -> Optional[Tuple[List[float], List[float]]]: """ Hidden function to obtain KM and WM scores from keywords :param seen_chunks_words: n-grams of words in doc :param all_tokens_chunks: list o...
__trainKMWM
identifier_name
ng-typeview.ts
Handler, defaultTagDirectiveHandlers, defaultAttrDirectiveHandlers} from "./ng-directives" import {extractControllerScopeInfo, extractCtrlViewConnsAngularModule, ControllerViewInfo, ControllerScopeInfo, ControllerViewConnector, defaultCtrlViewConnectors, CtrlViewFragmentExtractor, defaul...
function getViewTestFilename(ctrlFname: string, viewFname: string): string { return `${ctrlFname}_${viewFname}_viewtest.ts`; } async function processControllerView(prjSettings: ProjectSettings, controllerPath: string, viewPath: string, ngFilters: NgFilter[], tagDirectives: TagDirectiveHandler[], attr...
{ return "module " + moduleName + " {\n" + scopeInfo.imports.join("\n") + "\n" + scopeInfo.typeAliases.join("\n") + "\n" + scopeInfo.nonExportedDeclarations.join("\n") + "\n" + contents + "}\n"; }
identifier_body
ng-typeview.ts
DirectiveHandler, defaultTagDirectiveHandlers, defaultAttrDirectiveHandlers} from "./ng-directives" import {extractControllerScopeInfo, extractCtrlViewConnsAngularModule, ControllerViewInfo, ControllerScopeInfo, ControllerViewConnector, defaultCtrlViewConnectors, CtrlViewFragmentExtracto...
ngFilters: NgFilter[]; /** * List of controller-view connectors to use. * [[defaultCtrlViewConnectors]] contains a default list; you can use * that, add to that list, or specify your own. */ ctrlViewConnectors: ControllerViewConnector[]; /** * Hardcoded controller/view connectio...
random_line_split
ng-typeview.ts
Handler, defaultTagDirectiveHandlers, defaultAttrDirectiveHandlers} from "./ng-directives" import {extractControllerScopeInfo, extractCtrlViewConnsAngularModule, ControllerViewInfo, ControllerScopeInfo, ControllerViewConnector, defaultCtrlViewConnectors, CtrlViewFragmentExtractor, defaul...
const viewExprs = await parseView( prjSettings.resolveImportsAsNonScope || false, viewPath, scopeContents.viewFragments, scopeContents.importNames, Vector.ofIterable(tagDirectives), Vector.ofIterable(attributeDirectives), Vector.ofIterable(ngFilters)); const pathInfo = p...
{ // no point of writing anything if there is no scope block return; }
conditional_block
ng-typeview.ts
DirectiveHandler, defaultTagDirectiveHandlers, defaultAttrDirectiveHandlers} from "./ng-directives" import {extractControllerScopeInfo, extractCtrlViewConnsAngularModule, ControllerViewInfo, ControllerScopeInfo, ControllerViewConnector, defaultCtrlViewConnectors, CtrlViewFragmentExtracto...
(ctrlFname: string, viewFname: string): string { return `${ctrlFname}_${viewFname}_viewtest.ts`; } async function processControllerView(prjSettings: ProjectSettings, controllerPath: string, viewPath: string, ngFilters: NgFilter[], tagDirectives: TagDirectiveHandler[], attributeDirectives: AttributeDire...
getViewTestFilename
identifier_name
main_glcn.py
parser.add_argument('--method', default='vat') parser.add_argument('--lr', type=float, default=0.1) parser.add_argument('--in_channels', type=int, default=3) parser.add_argument('--out_channels', type=int, default=7) parser.add_argument('--topk', type=int, default=10) parser.add_argument('--ngcn_layers', type=int, def...
def eval(y_pred, y): # print(semi_outputs.shape) # y_pred = semi_outputs[num_labeled:(num_labeled+num_valid)] prob, idx = torch.max(y_pred, dim=1) return torch.eq(idx, y).float().mean() # Several Ways to initialize the weights # 1. initialize different weights using different initialization def weig...
model.train() # ce = nn.CrossEntropyLoss() # This criterion combines nn.LogSoftmax() and nn.NLLLoss() in one single class. # semi_outputs have been log_softmax, so only NLLLoss() here nll_loss = nn.NLLLoss() semi_outputs, loss_GL, S = model(x) # print("The learned S is ", torch.sum(S, dim=-1)) ...
identifier_body
main_glcn.py
parser.add_argument('--method', default='vat') parser.add_argument('--lr', type=float, default=0.1) parser.add_argument('--in_channels', type=int, default=3) parser.add_argument('--out_channels', type=int, default=7) parser.add_argument('--topk', type=int, default=10) parser.add_argument('--ngcn_layers', type=int, def...
# print("First Row of X") # print(x[0]) # print("Adj Matrix....") # print(S[S > 0]) return semi_outputs, loss, ce_loss def eval(y_pred, y): # print(semi_outputs.shape) # y_pred = semi_outputs[num_labeled:(num_labeled+num_valid)] prob, idx = torch.max(y_pred, dim=1) return torch.eq...
loss.backward() optimizer.step()
random_line_split
main_glcn.py
parser.add_argument('--method', default='vat') parser.add_argument('--lr', type=float, default=0.1) parser.add_argument('--in_channels', type=int, default=3) parser.add_argument('--out_channels', type=int, default=7) parser.add_argument('--topk', type=int, default=10) parser.add_argument('--ngcn_layers', type=int, def...
(m): """ Usage: model.apply(weights_init) :param m: :return: """ classname = m.__class__.__name__ if classname.find('Conv') != -1: m.weight.data.normal_(0.0, 0.02) elif classname.find('BatchNorm') != -1: m.weight.data.normal_(1.0, 0.02) m.bias.data.fill_(0) e...
weights_init
identifier_name
main_glcn.py
parser.add_argument('--method', default='vat') parser.add_argument('--lr', type=float, default=0.1) parser.add_argument('--in_channels', type=int, default=3) parser.add_argument('--out_channels', type=int, default=7) parser.add_argument('--topk', type=int, default=10) parser.add_argument('--ngcn_layers', type=int, def...
train_data = torch.cat(select_train_data, dim=0).to(opt.device) train_target = torch.cat(select_train_label, dim=0).to(opt.device) valid_data = torch.cat(select_val_data, dim=0).to(opt.device) valid_target = torch.cat(select_val_label, dim=0).to(opt.device) test_data = torch.cat(unlabeled_train_data, dim=0).to(opt.de...
label_mask = (train_target == label) current_label_X = train_data[label_mask] current_label_y = train_target[label_mask] select_train_data.append(current_label_X[:nSamples_per_class_train]) select_train_label.append(current_label_y[:nSamples_per_class_train]) select_val_data.append(current_label_X[n...
conditional_block
plot.go
averageLatency float64 periodicLatencies []analytics.PeriodicAvgLatency } func (sts *stats) fromPackets(packets []packet.Packet) { sts.averageLatency = analytics.CalcPositiveAverageLatency(packets) sts.periodicLatencies = analytics.CalcPeriodicAverageLatency(packets) } func maxPacketsValue(packets []packet.Pac...
random_line_split
plot.go
(packets []packet.Packet) { sts.averageLatency = analytics.CalcPositiveAverageLatency(packets) sts.periodicLatencies = analytics.CalcPeriodicAverageLatency(packets) } func maxPacketsValue(packets []packet.Packet) (xMin int64, xMax int64, yMin float64, yMax float64) { xMin, xMax = int64(1<<63-1), -int64(1<<63-1) yM...
fromPackets
identifier_name
plot.go
ackets) sts.periodicLatencies = analytics.CalcPeriodicAverageLatency(packets) } func maxPacketsValue(packets []packet.Packet) (xMin int64, xMax int64, yMin float64, yMax float64) { xMin, xMax = int64(1<<63-1), -int64(1<<63-1) yMin, yMax = float64(xMin), float64(xMax) for _, pkt := range packets { x := pkt.Receiv...
return nil } func verticalSteps(plot *plotter) (steps []float64) { plot.yLineStep = int64(math.Pow10(int(math.Ceil(math.Log10((plot.yMax-plot.yMin)/2))) - 1)) lo := plot.yLineStep * (int64(plot.yMin) / plot.yLineStep) hi := plot.yLineStep * (int64(plot.yMax) / plot.yLineStep) for y := lo; y <= hi; y += plot.yLineS...
return } }
conditional_block
plot.go
pdf.AddTTFFont("FiraSans-Book", "/usr/share/fonts/TTF/FiraSans-Book.ttf") if err != nil { return } err = pdf.AddTTFFont("FiraSans-Medium", "/usr/share/fonts/TTF/FiraSans-Medium.ttf") if err != nil { return } err = makeTitle(&pdf, plot.inputFilename) if err != nil { return } err = makeFootnote(&pdf, plo...
float64(pkt.ReceivedAt().UnixNano() - plot.xMin) y := pkt.Value() pdf.SetStrokeColor(pktColor(pkt)) xOnPaper := plot.xLeftMargin + x*plot.xScale yOnPaper := plot.yPaperSize - plot.yBottomMargin - (y-plot.yMin)*plot.yScale pdf.Line(xOnPaper, plot.yZeroAt, xOnPaper, yOnPaper) } func
identifier_body
cc.rs
it. let fat_ptr: [*mut (); 2] = unsafe { mem::transmute(&mut dummy as &mut dyn CcDyn) }; fat_ptr[1] } } impl CcDyn for CcDummy { fn gc_ref_count(&self) -> usize { 1 } fn gc_traverse(&self, _tracer: &mut Tracer) {} fn gc_clone(&self) -> Box<dyn GcClone> { panic!("bug...
; // safety: ccbox_ptr cannot be null from the above code. let non_null = unsafe { NonNull::new_unchecked(ccbox_ptr) }; let result = Self(non_null); if is_tracked { debug::log(|| (result.debug_name(), "new (CcBoxWithGcHeader)")); } else { debug::log(|| (re...
{ Box::into_raw(Box::new(cc_box)) }
conditional_block
cc.rs
#[inline] pub fn weak_count(&self) -> usize { self.inner().weak_count() } } impl<T: ?Sized, O: AbstractObjectSpace> RawCc<T, O> { #[inline] pub(crate) fn inner(&self) -> &RawCcBox<T, O> { // safety: CcBox lifetime maintained by ref count. Pointer is valid. unsafe { self.0.as...
cast_ref
identifier_name
cc.rs
it. let fat_ptr: [*mut (); 2] = unsafe { mem::transmute(&mut dummy as &mut dyn CcDyn) }; fat_ptr[1] } } impl CcDyn for CcDummy { fn gc_ref_count(&self) -> usize { 1 } fn gc_traverse(&self, _tracer: &mut Tracer) {} fn gc_clone(&self) -> Box<dyn GcClone> { panic!("bug...
} impl<T: Trace, O: AbstractObjectSpace> RawCc<T, O> { /// Constructs a new [`Cc<T>`](type.Cc.html) in the given /// [`ObjectSpace`](struct.ObjectSpace.html). /// /// To collect cycles, call `ObjectSpace::collect_cycles()`. pub(crate) fn new_in_space(value: T, space: &O) -> Self { let is_t...
{ collect::THREAD_OBJECT_SPACE.with(|space| Self::new_in_space(value, space)) }
identifier_body
cc.rs
/// Force drop the value T. fn gc_drop_t(&self); /// Returns the reference count. This is useful for verification. fn gc_ref_count(&self) -> usize; } /// A dummy implementation without drop side-effects. pub(crate) struct CcDummy; impl CcDummy { pub(crate) fn ccdyn_vptr() -> *mut () { let...
random_line_split
agent_test.py
agent did not explore enough nodes during the search; it " + \ "did not finish the first layer of available moves." TIMER_MARGIN = 15 # time (in ms) to leave on the timer to avoid timeout def curr_time_millis(): return 1000 * timeit.default_timer() def timeout(time_limit): """ Function deco...
@timeout(1) # @unittest.skip("Skip alpha-beta test.") # Uncomment this line to skip test def test_alphabeta(self): """ Test CustomPlayer.alphabeta """ h, w = 7, 7 method = "alphabeta" value_table = [[0] * w for _ in range(h)] value_table[2][5] = 1 value_ta...
agentUT, board = self.initAUT(depth, eval_fn, False, method, loc1=(2, 3), loc2=(0, 0)) move = agentUT.get_move(board, board.get_legal_moves(), lambda: 1e3) num_explored_valid = board.counts[0] == counts[idx][0] num_unique_valid = board.counts[1] == counts[idx][1] self.a...
conditional_block
agent_test.py
Your agent did not explore enough nodes during the search; it " + \ "did not finish the first layer of available moves." TIMER_MARGIN = 15 # time (in ms) to leave on the timer to avoid timeout def curr_time_millis(): return 1000 * timeit.default_timer() def timeout(time_limit): """ Function ...
set([(1, 4)]), set([(1, 4), (2, 5)])] counts = [(2, 2), (26, 13), (552, 36), (10564, 47)] for idx, depth in enumerate([1, 3, 5, 7]): agentUT, board = self.initAUT(depth, eval_fn, False, method, loc1=(0, 6), loc2=(0, 0)) move =...
random_line_split
agent_test.py
Your agent did not explore enough nodes during the search; it " + \ "did not finish the first layer of available moves." TIMER_MARGIN = 15 # time (in ms) to leave on the timer to avoid timeout def curr_time_millis(): return 1000 * timeit.default_timer() def timeout(time_limit): """ Function ...
move = agentUT.get_move(board, board.get_legal_moves(), lambda: 1e4) num_explored_valid = board.counts[0] <= counts[idx][0] num_unique_valid = board.counts[1] <= counts[idx][1] self.assertTrue(num_explored_valid, WRONG_NUM_EXPLORED.format(method, depth, ...
""" Test CustomPlayer.alphabeta """ h, w = 7, 7 method = "alphabeta" value_table = [[0] * w for _ in range(h)] value_table[2][5] = 1 value_table[0][4] = 2 value_table[1][0] = 3 value_table[5][5] = 4 eval_fn = EvalTable(value_table) expected_moves...
identifier_body
agent_test.py
agent did not explore enough nodes during the search; it " + \ "did not finish the first layer of available moves." TIMER_MARGIN = 15 # time (in ms) to leave on the timer to avoid timeout def curr_time_millis(): return 1000 * timeit.default_timer() def timeout(time_limit): """ Function deco...
(self): new_board = CounterBoard(self.__player_1__, self.__player_2__, width=self.width, height=self.height) new_board.move_count = self.move_count new_board.__active_player__ = self.__active_player__ new_board.__inactive_player__ = self.__inactive_player...
copy
identifier_name
zoekmachine.py
"14": "Kunst & Cultuur", "15": "Overig", '16': "Biologie", "17": "Wiskunde", "18": "Natuur- en scheikunde", "19": "Psychologie", "20": "Sociale wetenschap", "21": "Overig", "22": "Auto's", "23" : "Vliegtuigen", "24" : "Boten", "25" : "Openbaar vervoer", "26" : "Motorfi...
ttps://www.startpagina.nl/v/vraag/" + doc['_source']['Number'] + "/" title = doc['_source']['Question'] text = text + title if int(doc['_source']['Category']) == catNr: results.append(wrapinresults(url, title)) ma
conditional_block
zoekmachine.py
: "Persoon & Gezondheid", "3" : "Maatschappij", "4" : "Financiën & Werk", "5" : "Vervoer", "6" : "Computers & Internet", "7" : "Elektronica", "8" : "Entertainment & Muziek", "9" : "Eten & Drinken", "10": "Sport, Spel & Recreatie", '11': "Huis & Tuin", "12": "Wetenschap", "13"...
C2(term, c
identifier_name
zoekmachine.py
list_results[4], list_results[5], list_results[6], list_results[7], list_results[8], list_results[9]) f.write(whole) f.close() open_new_tab(filename) #Wrap results into hrefs to place in result blocks def wrapinresults(url, question): wrapper = """<p><a href=%s>%s</a></p>""" whole = wrapper % (ur...
fig, ax = plt.subplots() ax.bar(timeline, y, width = 10) fig.autofmt_xdate() plt.show() #Performs actual search def search(term, filter): text = '' quest = es.get(index="zoekmachine", doc_type="question", id=5)['_source'] #Connect to cloud and find results results = [] res = es.se...
y = range(len(timeline))
random_line_split
zoekmachine.py
_results[4], list_results[5], list_results[6], list_results[7], list_results[8], list_results[9]) f.write(whole) f.close() open_new_tab(filename) #Wrap results into hrefs to place in result blocks def wrapinresults(url, question): wrapper = """<p><a href=%s>%s</a></p>""" whole = wrapper % (url, qu...
#Ask user for query in which time setting def advanced(): print("What are you looking for? (ADV)") term = sys.stdin.readline() print("From what year on?") year = sys.stdin.readline() search(term, year) #Return that the choice was not available def invalid(): print("Not a valid choice") #Lis...
print("What are you looking for?") term = sys.stdin.readline() search(term, 0000)
identifier_body
bayes.py
所有词的出现数初始化为1, 并将分母初始化为2 """ p0Num = ones(numWords); p1Num = ones(numWords) # change to ones() p0Denom = 2.0; p1Denom = 2.0 # change to 2.0 for i in range(numTrainDocs): if trainCategory[i] == 1: # 2. (以下两行) 向量相加 p1Num += trainMatrix[i] ...
trainingSet = range(50); testSet=[] # create test set # (以下四行) 随机构建训练集
random_line_split
bayes.py
(侮辱性文档类)的单词。 """ """ 代码有4个输入: 要分类的向量vec2Classify以及使用函数trainNB0()计算得到的三个概率。 使用NumPy的数组来计算两个 向量相乘的结果❶。 这里的相乘是指对应元素相乘, 即先将两个向量中的第1个元素相乘, 然后将第2个元素相乘, 以此类推。 接下来将词汇表 中所有词的对应值相加, 然后将该值加到类别的对数概率上。 最后, 比较类别的概率返回大概率对应的类别标签。 这一切不是很难, 对吧? """ def classifyNB(vec2Classify, p0Vec, p1Vec, pClass1): # 1. 元素相乘 分类计算的核心 p1 = sum...
end(0)
identifier_name
bayes.py
testEntry)) print (testEntry,'classified as: ',classifyNB(thisDoc,p0V,p1V,pAb)) testEntry = ['stupid', 'garbage'] thisDoc = array(setOfWords2Vec(myVocabList, testEntry)) print (testEntry,'classified as: ',classifyNB(thisDoc,p0V,p1V,pAb)) # testingNB() # -----------------------------------使用朴素贝叶斯过滤垃圾...
conditional_block
bayes.py
testEntry)) print (testEntry,'classified as: ',classifyNB(thisDoc,p0V,p1V,pAb)) testEntry = ['stupid', 'garbage'] thisDoc = array(setOfWords2Vec(myVocabList, testEntry)) print (testEntry,'classified as: ',classifyNB(thisDoc,p0V,p1V,pAb)) # testingNB() # -----------------------------------使用朴素贝叶斯过滤垃圾...
identifier_body