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
downloadtaskmgr.go
InLDB := LoopTasksInLDB() if taskInLDB == nil { return nil } list := []*DownloadTask{} for _, v := range taskInLDB { list = append(list, v) } return list } func TaskSuccess(task *DownloadTask) { logger.Debug("Task Success", "id", task.Id) //从map中删除任务 DelTaskFromLDB(task.Id) DeleteDownloadingTask(task.Id...
{ nw, ew := dst.Write(buf[0:nr]) if nw > 0 { written += int64(nw) } if ew != nil { err = ew //fmt.Println(ew.Error()) if task.Status == Task_Break && (strings.Contains(err.Error(), "http: read on closed response body") || strings.Contains(err.Error(), "use of closed ne...
conditional_block
main.go
// OnError 错误报告函数定义 OnError func(err *Error) ) // Runner 结构体 type Runner struct { // 用于对外接口文档 APIInfo *graph.APIInfo // 用于执行服务 service *runner.Runners // 日志 log context.Log // logRegister 记录 api 注册过程 logRegister bool // 注册的信息 loaders []rj.Loader // 注入管理 injector *inject.InjectorManager // 请求参数管理 reque...
lt of [%s] not found", jr.Name) } return rsp, nil } // New 新建 Runner func New() *Runner { //log := logrus.Logger{ // Level: logrus.WarnLevel, // Formatter: &logrus.TextFormatter{}, //} return &Runner{ APIInfo: &graph.APIInfo{ Groups: nil, Request: map[string]*graph.ObjectInfo{}, Response: map[...
l, fmt.Errorf("resu
identifier_body
main.go
//} return &Runner{ APIInfo: &graph.APIInfo{ Groups: nil, Request: map[string]*graph.ObjectInfo{}, Response: map[string]*graph.ObjectInfo{}, }, log: &util.Logger{}, loaders: nil, service: runner.New(), injector: inject.NewManager(), requ...
loaderTyp, method.Name) if info != nil { svcInfo.Description = info.
conditional_block
main.go
// OnError 错误报告函数定义 OnError func(err *Error) ) // Runner 结构体 type Runner struct { // 用于对外接口文档 APIInfo *graph.APIInfo // 用于执行服务 service *runner.Runners // 日志 log context.Log // logRegister 记录 api 注册过程 logRegister bool // 注册的信息 loaders []rj.Loader // 注入管理 injector *inject.InjectorManager // 请求参数管理 reque...
oaders: nil, service: runner.New(), injector: inject.NewManager(), requestObjectManager: request.NewRequestObjectManager(), } } // Register 注册功能 func (r *Runner) Register(loaders ...rj.Loader) { r.loaders = append(r.loaders, loaders...) } // RegisterProvider 注册注入函数 func (...
l
identifier_name
main.go
// OnError 错误报告函数定义 OnError func(err *Error) ) // Runner 结构体 type Runner struct { // 用于对外接口文档 APIInfo *graph.APIInfo // 用于执行服务 service *runner.Runners // 日志 log context.Log // logRegister 记录 api 注册过程 logRegister bool // 注册的信息 loaders []rj.Loader // 注入管理 injector *inject.InjectorManager // 请求参数管理 reque...
r.afterExecute = fn return r } type results struct { response rj.Response run *Runner count int index int } // CallCount 调用个数 func (r *results) CallCount() int { return r.count } // CallIndex 调用次序 func (r *results) CallIndex() int { return r.index } func (r *results) Get(method interface{}) ([]*r...
// AfterExecute 在单个任务执行后拦截 func (r *Runner) AfterExecute(fn AfterExecute) *Runner {
random_line_split
sync.go
image-selector", "", "The image to search a pod for (e.g. nginx, nginx:latest, ${runtime.images.app}, nginx:${runtime.images.app.tag})") syncCmd.Flags().BoolVar(&cmd.Pick, "pick", true, "Select a pod") syncCmd.Flags().StringSliceVarP(&cmd.Exclude, "exclude", "e", []string{}, "Exclude directory from sync") syncCmd.F...
{ options = options.WithNamespace(cmd.Namespace) }
conditional_block
sync.go
") syncCmd.Flags().StringVar(&cmd.Path, "path", "", "Path to use (Default is current directory). Example: ./local-path:/remote-path or local-path:.") syncCmd.Flags().BoolVar(&cmd.DownloadOnInitialSync, "download-on-initial-sync", true, "DEPRECATED: Downloads all locally non existing remote files in the beginning") ...
random_line_split
sync.go
/pkg/util/factory" "github.com/loft-sh/devspace/pkg/util/survey" "github.com/pkg/errors" "github.com/spf13/cobra" ) // SyncCmd is a struct that defines a command call for "sync" type SyncCmd struct { *flags.GlobalFlags LabelSelector string ImageSelector string Container string Pod string Pick ...
upgrade.PrintUpgradeMessage(f.GetLog()) plugin.SetPluginCommand(cobraCmd, args) return cmd.Run(f) }, } syncCmd.Flags().StringVarP(&cmd.Container, "container", "c", "", "Container name within pod where to sync to") syncCmd.Flags().StringVar(&cmd.Pod, "pod", "", "Pod to sync to") syncCmd.Flags().StringVar...
{ cmd := &SyncCmd{GlobalFlags: globalFlags} syncCmd := &cobra.Command{ Use: "sync", Short: "Starts a bi-directional sync between the target container and the local path", Long: ` ############################################################################# ################### devspace sync ##################...
identifier_body
sync.go
/pkg/util/factory" "github.com/loft-sh/devspace/pkg/util/survey" "github.com/pkg/errors" "github.com/spf13/cobra" ) // SyncCmd is a struct that defines a command call for "sync" type SyncCmd struct { *flags.GlobalFlags LabelSelector string ImageSelector string Container string Pod string Pick ...
(f factory.Factory) error { if cmd.Ctx == nil { var cancelFn context.CancelFunc cmd.Ctx, cancelFn = context.WithCancel(context.Background()) defer cancelFn() } // Switch working directory if cmd.ConfigPath != "" { _, err := os.Stat(cmd.ConfigPath) if err != nil { return errors.Errorf("--config is spec...
Run
identifier_name
read_pool.rs
Extras; use yatp::task::future::TaskCell; /// A read pool. /// This is a wrapper around a yatp pool. /// It is used to limit the number of concurrent reads. pub struct ReadPool { pool: yatp::pool::Pool<TaskCell<ReadTask>>, pending_reads: Arc<Mutex<usize>>, pending_reads_gauge: IntGauge, } impl ReadPool ...
ReadPoolHandle::Yatp { remote, running_tasks, max_tasks, .. } => { let running_tasks = running_tasks.clone(); // Note that the running task number limit is not strict. // If several t...
{ let pool = match priority { CommandPri::High => read_pool_high, CommandPri::Normal => read_pool_normal, CommandPri::Low => read_pool_low, }; pool.spawn(f)?; }
conditional_block
read_pool.rs
Extras; use yatp::task::future::TaskCell; /// A read pool. /// This is a wrapper around a yatp pool. /// It is used to limit the number of concurrent reads. pub struct ReadPool { pool: yatp::pool::Pool<TaskCell<ReadTask>>, pending_reads: Arc<Mutex<usize>>, pending_reads_gauge: IntGauge, } impl ReadPool ...
remote: pool.remote().clone(), running_tasks: running_tasks.clone(), max_tasks: *max_tasks, pool_size: *pool_size, }, } } } #[derive(Clone)] pub enum ReadPoolHandle { FuturePools { read_pool_high: FuturePool, re...
pool, running_tasks, max_tasks, pool_size, } => ReadPoolHandle::Yatp {
random_line_split
read_pool.rs
Extras; use yatp::task::future::TaskCell; /// A read pool. /// This is a wrapper around a yatp pool. /// It is used to limit the number of concurrent reads. pub struct ReadPool { pool: yatp::pool::Pool<TaskCell<ReadTask>>, pending_reads: Arc<Mutex<usize>>, pending_reads_gauge: IntGauge, } impl ReadPool ...
( max_concurrent_reads: usize, remote: Remote, extras: Extras, pending_reads_gauge: IntGauge, ) -> Self { let pool = yatp::pool::Pool::new( max_concurrent_reads, remote, extras, ); Self { pool, pendin...
new
identifier_name
main.js
500, paginationSpeed : 500, singleItem : true, navigation : true, navigationText: [ "<i class='fa fa-angle-left'></i>", "<i class='fa fa-angle-right'></i>" ], afterInit : progressBar, afterMove : moved, startDragging : pauseOnDragging, //autoHeight : true, ...
} }); }); }; $('.animated-number').bind('inview', function(event, visible, visiblePartX, visiblePartY) { var $this = $(this); if (visible) { $this.animateNumbers($this.data('digit'), false, $this.data('duration')); $this.unbind('inview'); } }); }); // Contact form /*var form = ...
{ $this.text(stop); if (commas) { $this.text($this.text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")); } }
conditional_block
main.js
500, paginationSpeed : 500, singleItem : true, navigation : true, navigationText: [ "<i class='fa fa-angle-left'></i>", "<i class='fa fa-angle-right'></i>" ], afterInit : progressBar, afterMove : moved, startDragging : pauseOnDragging, //autoHeight : true, ...
$portfolio.isotope({ itemSelector : '.portfolio-item', layoutMode : 'fitRows' }); $portfolio_selectors.on('click', function(){ $portfolio_selectors.removeClass('active'); $(this).addClass('active'); var selector = $(this).attr('data-filter'); $portfolio.isotope({ filter: selector }); retur...
random_line_split
operator.go
]; !ok { o.wfr.Status.Stages[stage] = &v1alpha1.StageStatus{ Status: v1alpha1.Status{ Phase: v1alpha1.StatusRunning, }, } } o.wfr.Status.Stages[stage].Pod = podInfo } // UpdateStageOutputs updates stage outputs, they are key-value results from stage execution func (o *operator) UpdateStageOutputs(stag...
{ o.UpdateStageStatus(stg, &v1alpha1.Status{ Phase: v1alpha1.StatusCancelled, Reason: "GC", LastTransitionTime: metav1.Time{Time: time.Now()}, }) }
conditional_block
operator.go
Run() *v1alpha1.WorkflowRun { return o.wfr } // GetRecorder returns the event recorder. func (o *operator) GetRecorder() record.EventRecorder { return o.recorder } // InitStagesStatus initializes all missing stages' status to pending, and record workflow topology at this time to workflowRun status. func (o *operato...
} // Apply changes to latest WorkflowRun combined.Status.Cleaned = combined.Status.Cleaned || o.wfr.Status.Cleaned combined.Status.Overall = *resolveStatus(&combined.Status.Overall, &o.wfr.Status.Overall) for stage, status := range o.wfr.Status.Stages { s, ok := combined.Status.Stages[stage] if !ok { ...
{ if o.wfr == nil { return nil } // Update WorkflowRun status with retry. return retry.RetryOnConflict(retry.DefaultRetry, func() error { // Get latest WorkflowRun. latest, err := o.client.CycloneV1alpha1().WorkflowRuns(o.wfr.Namespace).Get(context.TODO(), o.wfr.Name, metav1.GetOptions{}) if err != nil { ...
identifier_body
operator.go
(clusterClient kubernetes.Interface, client k8s.Interface, wfr, namespace string) (Operator, error) { w, err := client.CycloneV1alpha1().WorkflowRuns(namespace).Get(context.TODO(), wfr, metav1.GetOptions{}) if err != nil { return nil, err } return &operator{ clusterClient: clusterClient, client: clien...
newFromName
identifier_name
operator.go
("Process workload error: ", err) } else { log.WithField("wfr", o.wfr.Name).WithField("stg", stage).Error("Process workload error: ", err) } continue } } if len(retryStageNames) > 0 { var requeue bool if HasTimedOut(o.wfr) { // timed-out. Update stage status and do not requeue for _, stageNam...
}
random_line_split
flatdb.go
. // // All items stored in the flatDB will be marshalled in this format: // // +------------+-----+--------------+-------+ // | Key Length | Key | Value Length | Value | // +------------+-----+--------------+-------+ // // The flatDB can only be opened for read only mode(iteration) or write only // mode. Each wr...
if n != len(db.buff) { return ErrWriteFailure } db.buff = db.buff[:0] db.items = 0 // Step two, flush chunk offset var local [8]byte binary.BigEndian.PutUint64(local[:], db.offset) n, err = db.index.Write(local[:]) if err != nil { return err } if n != 8 { return ErrWriteFailure } return nil } func ...
n, err := db.data.Write(db.buff) if err != nil { return err }
random_line_split
flatdb.go
data, index: index, read: read, }, nil } // Has retrieves if a key is present in the flat data store. func (db *FlatDatabase) Has(key []byte) (bool, error) { panic("not supported") } // Get retrieves the given key if it's present in the flat data store. func (db *FlatDatabase) Get(key []byte) ([]byte, error) ...
{ return iter.key }
identifier_body
flatdb.go
err = os.OpenFile(filepath.Join(path, syncedName), os.O_RDONLY, 0644) if err != nil { return nil, err } index, err = os.OpenFile(filepath.Join(path, indexName), os.O_RDONLY, 0644) if err != nil { return nil, err } } else { data, err = os.OpenFile(filepath.Join(path, temporaryName), os.O_WRONLY|os.O_...
{ return false }
conditional_block
flatdb.go
// // All items stored in the flatDB will be marshalled in this format: // // +------------+-----+--------------+-------+ // | Key Length | Key | Value Length | Value | // +------------+-----+--------------+-------+ // // The flatDB can only be opened for read only mode(iteration) or write only // mode. Each writ...
() { fb.lock.Lock() defer fb.lock.Unlock() fb.keysize, fb.valsize = 0, 0 fb.keys = fb.keys[:0] fb.vals = fb.vals[:0] } // NewIterator creates a iterator over the **whole** database with first-in-first-out
Reset
identifier_name
write.rs
which is odd, and std::u{N}::MAX + 1 == 0 is even. // // note also that `ri` _may_ have been re-used since we last read into last_epochs. // this is okay though, as a change still implies that the new reader must have // arrived _after_ we did the atomic ...
{ // Safety: we know there are no outstanding w_handle readers, since we haven't // refreshed ever before, so we can modify it directly! let mut w_inner = self.raw_write_handle(); let w_inner = unsafe { w_inner.as_mut() }; let r_handle = self.enter().expect("m...
conditional_block
write.rs
<T>; fn deref(&self) -> &Self::Target { &self.r_handle } } impl<T, O> Extend<O> for WriteHandle<T, O> where T: Absorb<O>, { /// Add multiple operations to the operational log. /// /// Their effects will not be exposed to readers until you call [`publish`](Self::publish) fn extend<I>...
{ let (mut w, _) = crate::new::<i32, _>(); // Until we refresh, writes are written directly instead of going to the // oplog (because there can't be any readers on the w_handle table). assert!(!w.has_pending_operations()); w.publish(); assert!(!w.has_pending_operations()...
identifier_body
write.rs
writes in the oplog // the r_handle copy has not seen any of the writes following swap_index if self.swap_index != 0 { // we can drain out the operations that only the w_handle copy needs // // NOTE: the if above is because drain(0..0) would remov...
assert_eq!(w.oplog.len(), 2); }
random_line_split
write.rs
<T, O> where T: Absorb<O>, { epochs: crate::Epochs, w_handle: NonNull<T>, oplog: VecDeque<O>, swap_index: usize, r_handle: ReadHandle<T>, last_epochs: Vec<usize>, #[cfg(test)] refreshes: usize, #[cfg(test)] is_waiting: Arc<AtomicBool>, /// Write directly to the write hand...
WriteHandle
identifier_name
moveit_grasp.py
0.02 # push the gripper forward to grasp objects more self.is_clear_octomap = True ## ROS init self.init_ROS_and_moveit() ## robot start working self.get_basic_info() # rospy.logwarn("Type in 'start' to set robot arm in home position, and start working... ") ...
self.group.stop() self.group.clear_pose_targets() ## approach -> close gripper -> retreive -> go home if plan: # self.clear_octomap() # self.open_gripper() self.approach_eef(pose_grasp) self.close_gripper() self.retrie...
rospy.logerr("****** mico_arm pregrasp || plan failed ******")
conditional_block
moveit_grasp.py
0.02 # push the gripper forward to grasp objects more self.is_clear_octomap = True ## ROS init self.init_ROS_and_moveit() ## robot start working self.get_basic_info() # rospy.logwarn("Type in 'start' to set robot arm in home position, and start working... ") ...
(self, config=0): current_joint_values = self.group.get_current_joint_values() if config == 0: ## home config 0 - prefered home joint values current_joint_values[0] = -0.5024237154549698 current_joint_values[1] = -0.0461999859584763 current_joint_values[2...
set_home_joint_values
identifier_name
moveit_grasp.py
0.02 # push the gripper forward to grasp objects more self.is_clear_octomap = True ## ROS init self.init_ROS_and_moveit() ## robot start working self.get_basic_info() # rospy.logwarn("Type in 'start' to set robot arm in home position, and start working... ") ...
def clear_octomap(self): rospy.loginfo("Clearing Octomap...") rospy.wait_for_service("/clear_octomap") try: client = rospy.ServiceProxy("/clear_octomap", Empty) client() except rospy.ServiceException as e: print ("Service call failed: %s"%e) ...
''' transform grasp pose from grasp_frame to mdworld_frame ''' ## tf transform tf_buffer = tf2_ros.Buffer(rospy.Duration(10.0)) # tf buffer length tf_listener = tf2_ros.TransformListener(tf_buffer) # try: transform_grasp_world = tf_buffer.lookup_transform( ...
identifier_body
moveit_grasp.py
0.02 # push the gripper forward to grasp objects more self.is_clear_octomap = True ## ROS init self.init_ROS_and_moveit() ## robot start working self.get_basic_info() # rospy.logwarn("Type in 'start' to set robot arm in home position, and start working... ") ...
# self.go_home(config=1) self.go_home(config=0) self.open_gripper() if self.is_clear_octomap: self.clear_octomap() def open_gripper(self): gripper_goal = self.group_gripper.get_current_joint_values() gripper_goal[0] = 0.2 gripper_goal[1] = 0.2...
random_line_split
Form.py
= getattr(MCWidgets.Widgets, widget_type) import Widget if not issubclass(widget_type, Widget.Widget): raise WidgetTypeNotValid, 'Widget type %s is not valid' % type if name in self._widgets: raise WidgetDuplicated, 'Widget "%s" have been already added' % name ...
rm.render_widget(wid) except: import traceback, sys traceback.print_exc(file = sys.stderr) raise return self.__cache[wid] def get_nam
conditional_block
Form.py
Devuelve el argumento pedido. Si no lo encuentra, devuelve default''' return self._args.get(arg, default) def set_arg(self, arg, value): '''set_arg(arg, value) Cambia el valor del argumento indicado''' self._args[arg] = value # Propiedades. Se usan para los widgets p...
s(self): '''_get_url_static_files() -> str Devuelve la url donde están los ficheros estáticos para, los widgets, como CSS, JavaScript, imágenes, etc''' return self._args.get('url_static_files', '/staticmcw/') def _make_var_name(self, widget, varname): '''_make_var_name (wi...
Devuelve el nombre del formulario''' return self._form_name def _get_url_static_file
identifier_body
Form.py
Devuelve el argumento pedido. Si no lo encuentra, devuelve default''' return self._args.get(arg, default) def set_arg(self, arg, value): '''set_arg(arg, value) Cambia el valor del argumento indicado''' self._args[arg] = value # Propiedades. Se usan para los widgets p...
def _type_initialized(self, typename): '''_type_initialized (type) -> bool Devuelve True si el tipo de widget indicado ya está inicializado''' return typename in self._initialized_types
ellos.''' # damos por hecho de que el nombre de la variables # no contiene caracteres problemáticos return '_'.join([self._form_name, widget, varname])
random_line_split
Form.py
): '''add_widget(widget_type, name, args = {}) Añade un widget al formulario, del tipo widget_type. widget_type debe ser una clase derivada de Widget. name se usa para referirse al widget, o una cadena para buscar en el paquete MCWidgets.Widgets ''' if isinsta...
s import html_d
identifier_name
customdomain_utils.go
1.ConditionStatus, newReason, newMessage string, updateConditionCheck UpdateConditionCheck, ) bool { if oldStatus != newStatus { return true } return updateConditionCheck(oldReason, oldMessage, newReason, newMessage) } // SetCustomDomainCondition sets a condition on a CustomDomain resource's status func SetCusto...
else { reqLogger.Info(fmt.Sprintf("Secret %s did not have proper labels, skipping.", ingressSecret.Name)) } } // get and delete the custom ingresscontroller customIngress := &operatorv1.IngressController{} err = r.Client.Get(context.TODO(), types.NamespacedName{ Namespace: ingressOperatorNamespace, Name:...
{ err = r.Client.Delete(context.TODO(), ingressSecret) if err != nil { reqLogger.Error(err, fmt.Sprintf("Failed to delete %s secret", instance.Name)) return err } }
conditional_block
customdomain_utils.go
ConditionType, status corev1.ConditionStatus, message string, updateConditionCheck UpdateConditionCheck, ) []customdomainv1alpha1.CustomDomainCondition { now := metav1.Now() existingCondition := FindCustomDomainCondition(conditions, conditionType) if existingCondition == nil { if status == corev1.ConditionTrue ...
}
random_line_split
customdomain_utils.go
existingCondition == nil { if status == corev1.ConditionTrue { conditions = append( conditions, customdomainv1alpha1.CustomDomainCondition{ Type: conditionType, Status: status, Reason: string(conditionType), Message: message, LastTr...
{ for _, v := range list { if v == s { return true } } return false }
identifier_body
customdomain_utils.go
// Error reading the object - requeue the request. return reconcile.Result{}, err } delete(customIngress.Labels, managedLabelName) customIngress.Spec.NodePlacement = &operatorv1.NodePlacement{ NodeSelector: &metav1.LabelSelector{ MatchLabels: map[string]string{"node-role.kubernetes.io/worker": ""}, }, T...
isUsingNewManagedIngressFeature
identifier_name
codec.rs
/// `f` parity columns, where one or more columns is missing, reconstruct /// the data from the missing columns. Takes as a parameter exactly `k` /// surviving columns, even if more than `k` columns survive. These *must* /// be the lowest `k` surviving columns. For example, in a 5+3 array where /...
/// Reconstruct missing data from partial surviving columns /// /// Given a `Codec` with `m` total columns composed of `k` data columns and
random_line_split
codec.rs
Exactly `k` columns of surviving data and parity, /// sorted in order of the original column index, with /// data columns preceding parity columns. /// - `missing`: Reconstructed data (not parity!) columns. The /// number should be no ...
for j in 0..k { dec_rows[k * i + j] = dec_matrix[k * r + j]; } } // Finally generate the fast encoding tables isa_l::ec_init_tables(k as u32, errs as u32, &dec_rows, &mut dec_tables); dec_tables } /// Return the degre...
{ break; // Exclude missing parity columns }
conditional_block
codec.rs
(&self, _len: usize, _data: &[*const u8], _parity: &[*const u8]) -> FixedBitSet { panic!("Unimplemented"); } /// Reconstruct missing data from partial surviving columns /// /// Given a `Codec` with `m` total columns composed of `k` data columns and /// `f` parity columns, w...
check
identifier_name
codec.rs
Exactly `k` columns of surviving data and parity, /// sorted in order of the original column index, with /// data columns preceding parity columns. /// - `missing`: Reconstructed data (not parity!) columns. The /// number should be no ...
data.push(column); } for _ in 0..maxparity { let column = vec![0u8; len]; parity.push(column); } for _ in 0..(maxparity as usize) { reconstructed.push(vec![0u8; len]); } for cfg in &cfgs { let m = cfg.0; ...
{ let cfgs = [ (3, 1), (9, 1), (4, 2), (10, 2), (6, 3), (19, 3), (8, 4), (20, 4) ]; let len = 64; let maxdata = 28; let maxparity = 4; let mut rng = rand::thread_rng(); let mut data = Vec::<Vec<u8>>::new(); ...
identifier_body
treerunner.js
dirty = false; fn = lQueue.shift(); while (fn) { fn(); fn = lQueue.shift(); } } function nextTick (fn) { queue.push(fn); if (dirty) return; dirty = true; trigger(); } if (hasPostMessage) { trigger = function () { window.postMessage(m...
// -- in a next-tick, create a new TreeDownloader at the new child (async) // -- -- on complete, decrement children count by 1 // -- -- when children count hits 0, call downloadComplete() if (rootParent) { rootData.resolvedId = this.env.rulesEngine.resolveModule(rootData.originalId, root...
// -- transform the contents (rules) // -- assign file to child // -- extract requires // -- for each child, create children, up the children count by 1
random_line_split
treerunner.js
function nextTick (fn) { queue.push(fn); if (dirty) return; dirty = true; trigger(); } if (hasPostMessage) { trigger = function () { window.postMessage(messageName, '*'); }; processQueue = function (event) { if (event.source == window && event.data === mess...
{ var lQueue = queue; queue = []; dirty = false; fn = lQueue.shift(); while (fn) { fn(); fn = lQueue.shift(); } }
identifier_body
treerunner.js
dirty = false; fn = lQueue.shift(); while (fn) { fn(); fn = lQueue.shift(); } } function nextTick (fn) { queue.push(fn); if (dirty) return; dirty = true; trigger(); } if (hasPostMessage) { trigger = function () { window.postMessage(m...
(err) { next(err, contents); } try { fn(onData, contents, commFlowResolver, commFlowCommunicator, { moduleId: nodeData.originalId, parentId: (parentData) ? parentData.originalId : '', parentUrl: (parentData...
onError
identifier_name
credit_pipe.py
#converts a string that is camelCase into snake_case #https://stackoverflow.com/questions/1175208/elegant-python-function-to-convert-camelcase-to-snake-case def camel_case(column_name): s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', column_name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() #Give data ...
return pd.read_csv(csv_file,nrows=nrows)
identifier_body
credit_pipe.py
aling with missing data def clean_miss(data_frame): missing_data = miss_data(data_frame) data_frame = data_frame.drop((missing_data[missing_data['Total'] > 1]).index,1) data_frame.isnull().sum().max() #just checking that there's no missing data missing... return data_frame #Univariate analysis - scalin...
(data_frame, var_scale): data_scaled = StandardScaler().fit_transform(data_frame[var_scale][:,np.newaxis]); low_range = data_scaled[data_scaled[:,0].argsort()][:10] high_range= data_scaled[data_scaled[:,0].argsort()][-10:] print('outer range (low) of the distribution:') print(low_range) print('\...
scale
identifier_name
credit_pipe.py
the rest of the potential hyphens for i in range(1, len(var_list)): if '-' in var_list[i]: formula = formula + "+"+'Q("'+var_list[i]+'")' else: formula = formula + "+"+ var_list[i] y, X = dmatrices(formula,data_frame, return_type="dataframe") y = np.ravel(y) mode...
update_window = 12
random_line_split
credit_pipe.py
dataframe_1 def get_combos(param_grid_dict): all = sorted(param_grid_dict) all_combos=[] combinations = it.product(*(param_grid_dict[Name] for Name in all)) for i in combinations: lil_combo = {} for iter,key in enumerate(all): lil_combo[key] = i[iter] all_combos.app...
test_start_time = test_end_time - relativedelta(months=+prediction_window) train_end_time = test_start_time - relativedelta(days=+1) # minus 1 day train_start_time = train_end_time - relativedelta(months=+prediction_window) while (train_start_time >= start_time_date ): ...
conditional_block
blockchain.go
type Block struct { Index int Timestamp int64 Proof int PreviousHash string Difficulty string } // add a function to the blockchain struct to get the previous block func (bc *Blockchain) GetPreviousBlock() Block { return bc.Chain[len(bc.Chain) - 1] } // function to print block information, no...
// a->f if val > 96 { val -= 96-9 } else { val -= 48 } if carry { val -=1 carry = false } if (val+1) == 0 { val = 15 carry = true } if val >= 10 { r[i] = val+96-9 ...
{ r[i] = val continue }
conditional_block
blockchain.go
type Block struct { Index int Timestamp int64 Proof int PreviousHash string Difficulty string } // add a function to the blockchain struct to get the previous block func (bc *Blockchain) GetPreviousBlock() Block { return bc.Chain[len(bc.Chain) - 1] } // function to print block information, no...
// add a function to the blockchain struct to create a hash func (bc *Blockchain) HashBlock(block Block) string { var hash = sha256.New() hash.Write([]byte(strconv.Itoa(block.Index) + time.Unix(block.Timestamp, 0).Format(time.UnixDate) + strconv.Itoa(block.Proof) + ...
{ newBlock := new(Block) newBlock.Proof, newBlock.Timestamp = bc.ProofOfWork() //newBlock.Timestamp = time.Now().Unix() newBlock.Index = len(bc.Chain) newBlock.PreviousHash = bc.HashBlock(bc.Chain[len(bc.Chain) - 1]) newBlock.Difficulty = bc.AdjustDifficulty() bc.BlockMutex.Lock() bc.Ch...
identifier_body
blockchain.go
type Block struct { Index int Timestamp int64 Proof int PreviousHash string Difficulty string } // add a function to the blockchain struct to get the previous block func (bc *Blockchain) GetPreviousBlock() Block { return bc.Chain[len(bc.Chain) - 1] } // function to print block information, no...
() { newBlock := new(Block) newBlock.Proof, newBlock.Timestamp = bc.ProofOfWork() //newBlock.Timestamp = time.Now().Unix() newBlock.Index = len(bc.Chain) newBlock.PreviousHash = bc.HashBlock(bc.Chain[len(bc.Chain) - 1]) newBlock.Difficulty = bc.AdjustDifficulty() bc.BlockMutex.Lock() bc...
AddBlock
identifier_name
blockchain.go
fmt.Println("Proof of the block is " + strconv.Itoa(block.Proof)) fmt.Println("Hash of the previous block is " + block.PreviousHash) fmt.Println("Hash of the current block is " + bc.HashBlock(block)) fmt.Println("Difficulty of the block is " + block.Difficulty) fmt.Println("\n\n") } // Increment he...
return false } //verify time stamp if block.Timestamp < prev_block.Timestamp { fmt.Println("the new block had a bad timestamp")
random_line_split
daal_pca_test.py
.521547782, -0.418681224], [0.316721742, 0.288319245, 0.499514144, 0.267566455, -0.0338341451, -0.134086469, -0.184724393, -0.246523528, 0.593753078, -0.169969303], [0.315335647, -0.258529064, 0.374780341, -0.169762381, 0.416093803, -0.118232778, 0.445019707, -0.395962728...
2], 6)), abs(round(self.expected_R_singular_vec[ind][ind2], 6))) def test_daal_pca_bad_no_of_k(self): """Test invalid k value in
conditional_block
daal_pca_test.py
762, 0.110951688, 0.102784186, 0.292018251, 0.109836478], [0.315542865, -0.236497774, -0.289051199, -0.452795684, -0.12175352, 0.5265342, -0.0312645934, -0.180142504, 0.318334436, -0.359303747], [0.315875856, 0.72196434, -0.239088332, -0.0259999274, -0.057915355...
xception, "columns must be a list of strings"): self.context.daaltk.models.dimreduction.pca.train(self.frame, 10, k=10) if __name__ == '__main__': unittest.main()
identifier_body
daal_pca_test.py
9] # expected right-singular vectors V expected_R_singular_vec = \ [[0.315533916, -0.3942771, 0.258362247, -0.0738539198, -0.460673735, 0.0643077298, -0.0837131184, 0.0257963888, 0.00376728499, 0.669876972], [0.316500921, -0.165508013, -0.131017612, 0.581988787, -0...
pca_train_out = self.context.daaltk.models.dimreduction.pca.train(self.frame, ["X1", "X2", "X3", "X4", "X5", "X6", "X7", "X8", "X9", "X10"], True, 10) # actual right-singular vectors a...
ctionality with mean centering"""
identifier_name
daal_pca_test.py
1, -0.165508013, -0.131017612, 0.581988787, -0.0863507191, 0.160473134, 0.53134635, 0.41199152, 0.0823770991, -0.156517367], [0.316777341, 0.244415549, 0.332413311, -0.377379981, 0.149653873, 0.0606339992, -0.163748261, 0.699502817, -0.171189721, -0.124509149], ...
"X6", "X7", "X8", "X9", "X10"], False, 10) # actual right-singular vectors
random_line_split
level.rs
; pub struct LevelScene { done: bool, car: warmy::Res<resources::Image>, map: Map, player_entity: specs::Entity, dispatcher: specs::Dispatcher<'static, 'static>, } impl LevelScene { pub fn new(ctx: &mut ggez::Context, world: &mut World) -> Self { let done = false; let car = wor...
fn update_collisions(&mut self, world: &mut World) { let mut collide_world = world.specs_world.write_resource::<nc::world::CollisionWorld<f32, specs::Entity>>(); collide_world.update(); let mut motions = world.specs_world.write_storage::<c::Motion>(); // gameworld.collide_world....
{ let builder = specs::DispatcherBuilder::new() .with(MovementSystem, "sys_movement", &[]) .with(CollisionSystem, "sys_collision", &[]); // builder.add_thread_local(RenderSystem); builder.build() }
identifier_body
level.rs
0; pub struct LevelScene { done: bool, car: warmy::Res<resources::Image>, map: Map, player_entity: specs::Entity, dispatcher: specs::Dispatcher<'static, 'static>, } impl LevelScene { pub fn new(ctx: &mut ggez::Context, world: &mut World) -> Self { let done = false; let car = wo...
// motion.velocity = rotation.transform_vector(&player_motion.acceleration); } } ncollide2d::pipeline::narrow_phase::ContactEvent::Stopped(handle1, handle2) => { println!("contact ended"); ...
{ println!("contact started!"); // look up collision object let obj1 = collide_world.collision_object(*handle1).expect("missing coll obj1"); // look up entity let entity1: &specs::Entity = obj1.data(...
conditional_block
level.rs
; pub struct LevelScene { done: bool, car: warmy::Res<resources::Image>, map: Map, player_entity: specs::Entity, dispatcher: specs::Dispatcher<'static, 'static>, } impl LevelScene { pub fn new(ctx: &mut ggez::Context, world: &mut World) -> Self { let done = false; let car = wor...
fn update(&mut self, gameworld: &mut World, _ctx: &mut ggez::Context) -> scenes::Switch { self.dispatcher.dispatch(&mut gameworld.specs_world.res); self.update_collisions(gameworld); if self.done { scene::SceneSwitch::Pop } else { scene::SceneSwitch::None ...
// fn camera_draw(ctx: &mut ggez::Context, drawable: &graphics::Drawable, params: graphics::DrawParam) -> ggez::GameResult<()> { // Ok(()) // } impl scene::Scene<World, input::Event> for LevelScene {
random_line_split
level.rs
0; pub struct LevelScene { done: bool, car: warmy::Res<resources::Image>, map: Map, player_entity: specs::Entity, dispatcher: specs::Dispatcher<'static, 'static>, } impl LevelScene { pub fn new(ctx: &mut ggez::Context, world: &mut World) -> Self { let done = false; let car = wo...
() -> specs::Dispatcher<'static, 'static> { let builder = specs::DispatcherBuilder::new() .with(MovementSystem, "sys_movement", &[]) .with(CollisionSystem, "sys_collision", &[]); // builder.add_thread_local(RenderSystem); builder.build() } fn update_collisions(&...
register_systems
identifier_name
lib.rs
::Start => { svg_text.assign("text-anchor", "start"); } Anchor::Middle => { svg_text.assign("text-anchor", "middle"); } Anchor::End => { svg_text.assign("text-anchor", "end"); } }; let text_node = TextNode::new(s); svg_text.append(...
} y += 1; } (svg_elements, relines, get_styles()) } /// parse the memes and return the svg together with the unmatched strings fn line_to_svg_with_excess_str(y: usize, s: &str, settings:&Settings) -> Option<(Vec<Box<Node>>, String)>{ let body = parse_memes(s); if body.has_memes(){ ...
{ relines.push_str(line); relines.push('\n'); }
conditional_block
lib.rs
(s: &str, x: f32, y: f32, settings: &Settings, anchor: Anchor) -> SvgText { to_svg_text_pixel_escaped(&escape_str(s), x, y, settings, anchor) } fn to_svg_text_pixel_escaped(s: &str, x: f32, y: f32, settings: &Settings, anchor: Anchor) -> SvgText { let (offsetx, offsety) = settings.offset(); let sx = x + of...
to_svg_text_pixel
identifier_name
lib.rs
) .set("class", "donger") .set("r", c.r) } } #[derive(Debug)] struct Circle{ cx: f32, cy: f32, r: f32, } /// detect whether the series of string could be a meme /// has at least 1 full width character (width = 2) /// has at least 1 zero sized width character (width = 0) /// h...
} } fn regroup_rest_text(rest_text: &Vec<(usize, String)>)->Vec<(usize, String)>{
random_line_split
utils.py
角坐标] 格式 pred:网络输出,tensor anchors: 是一个list。表示锚框的大小。 YOLOv2官方配置文件中,anchors = [0.57273, 0.677385, 1.87446, 2.06253, 3.33843, 5.47434, 7.88282, 3.52778, 9.77052, 9.16828], 表示有5个锚框,第一个锚框大小[w, h]是[0.57273, 0.677385],第5个锚框大小是[9.77052, 9.16828] 锚框的大小都是表示在特征图13x13中的大小 num_cl...
gt_h = gt_bboxs[:, :, 4] gtx_min = gt_center_x - gt_w / 2.0 gtx_max = gt_center_x + gt_w / 2.0 gty_min = gt_center_y - gt_h / 2.0 gty_max = gt_center_y + gt_h / 2.0
random_line_split
utils.py
] gt_bbox[i, 2] = bbox[i*5+2] gt_bbox[i, 3] = bbox[i*5+3] gt_bbox[i, 4] = bbox[i*5+4] if i >= max_num: break return gt_bbox def calculate_iou(bbox1,bbox2): """计算bbox1=(x1,y1,x2,y2)和bbox2=(x3,y3,x4,y4)两个bbox的iou""" intersect_bbox = [0., 0., 0., 0.] # bb...
85, 1.87446, 2.06253, 3.33843, 5.47434, 7.88282, 3.52778, 9.77052, 9.16828], 表示有5个锚框,第一个锚框大小[w, h]是[0.57273, 0.677385],第5个锚框大小是[9.77052, 9.16828] 锚框的大小都是表示在特征图13x13中的大小 num_classes:类别数 返回预测框pred_box, 最终输出数据保存在pred_box中,其形状是[N, num_anchors, 4, H, W,],4表示4个位置坐标 """ num_rows...
6773
conditional_block
utils.py
gt_bbox[i, 2] = bbox[i*5+2] gt_bbox[i, 3] = bbox[i*5+3] gt_bbox[i, 4] = bbox[i*5+4] if i >= max_num: break return gt_bbox def calculate_iou(bbox1,bbox2): """计算bbox1=(x1,y1,x2,y2)和bbox2=(x3,y3,x4,y4)两个bbox的iou""" intersect_bbox = [0., 0., 0., 0.] # bbox1...
# 将坐标从xywh转化成xyxy,也就是 [左上角坐标,右上角坐标] 格式 pred_box[:, :, :, :, 0] = pred_box[:, :, :, :, 0] - pred_box[:, :, :, :, 2] / 2. pred_box[:, :, :, :, 1] = pred_box[:, :, :, :, 1] - pred_box[:, :, :, :, 3] / 2. pred_box[:, :, :, :, 2] = pred_box[:, :, :, :, 0] + pred_box[:, :, :, :, 2] pred_box[:, :, :,...
anchors_this.append([anchors[ind * 2], anchors[ind * 2 + 1]]) # anchors_this = np.array(anchors_this).astype('float32') anchors_this = paddle.to_tensor(anchors_this) pred_box = paddle.zeros(pred_location.shape) # for b in range(batchsize): for i in range(num_rows): for j in ra...
identifier_body
utils.py
max = np.float64(xmax) ymax = np.float64(ymax) if xmax == xmin or ymax == ymin: print(xml_file) dataset.append([xmax - xmin, ymax - ymin]) # 宽与高的相对值 return np.array(dataset) # 转为numpy数组 def bbox2tensor(bbox,max_num=30): ''' bbox:标签信息。信息格式为[cl...
x
identifier_name
td_learning.py
alpha_fig3 = 0.001 color_fig3 = '#da008a' # Parameters for generating figure 4 training_sets_fig4 = 100 training_sequences_fig4 = 10 alphas_fig4 = np.array(range(70)) / 100 lambdas_fig4 = [0, 0.3, 0.8, 1.0] colors_fig4 = ['#da008a', '#7400e3', '#009bdf', '#c5c23d'] # Parameters for generating figure 5 training_sets_...
um_steps, start_step, seq_per_set, num_sets, seed=-1): """ Create a list of lists of training sequences for random walks. :param num_steps: The number of steps in the random walk :param start_step: The starting step of the sequences. -1 for random :param seq_per_set: Number of training sequences in ...
ke_a_walk(n
identifier_name
td_learning.py
alpha_fig3 = 0.001 color_fig3 = '#da008a' # Parameters for generating figure 4 training_sets_fig4 = 100 training_sequences_fig4 = 10 alphas_fig4 = np.array(range(70)) / 100 lambdas_fig4 = [0, 0.3, 0.8, 1.0] colors_fig4 = ['#da008a', '#7400e3', '#009bdf', '#c5c23d'] # Parameters for generating figure 5 training_sets_...
else: # Non-terminal state delta_p = np.dot(p, training[step + 1, :]) - np.dot(p, training[step, :]) if verbose: print('delta_p =', delta_p) delta_w += alpha * delta_p * np.sum(these_steps * lambda_seq[:, None], axis=0) if verbose: print('delta_w =', delta_w) lambda_se...
verbose: print("z =", z) delta_p = z - np.dot(p, training[-1, :])
conditional_block
td_learning.py
0 alpha_fig3 = 0.001 color_fig3 = '#da008a' # Parameters for generating figure 4 training_sets_fig4 = 100 training_sequences_fig4 = 10 alphas_fig4 = np.array(range(70)) / 100 lambdas_fig4 = [0, 0.3, 0.8, 1.0] colors_fig4 = ['#da008a', '#7400e3', '#009bdf', '#c5c23d'] # Parameters for generating figure 5 training_sets...
this_sequence[step] = 1 # Add this step to the sequence sequence = np.vstack((sequence, this_sequence)) # Assign the sequence to its position in the training data training[this_set][seq] = sequence return training #----------------------------...
# Generate the vector representing this step this_sequence = np.zeros(num_steps).astype(int) # Set the appropriate element to 1
random_line_split
td_learning.py
alpha_fig3 = 0.001 color_fig3 = '#da008a' # Parameters for generating figure 4 training_sets_fig4 = 100 training_sequences_fig4 = 10 alphas_fig4 = np.array(range(70)) / 100 lambdas_fig4 = [0, 0.3, 0.8, 1.0] colors_fig4 = ['#da008a', '#7400e3', '#009bdf', '#c5c23d'] # Parameters for generating figure 5 training_sets_...
step = start_step sequence = np.zeros(num_steps).astype(int) sequence[step] = 1 while (step != 0 and step != num_steps - 1): # While not in absorbing state if np.random.uniform() >= 0.5: # Uniformly random L v R step step += 1 # Go righ...
" Create a list of lists of training sequences for random walks. :param num_steps: The number of steps in the random walk :param start_step: The starting step of the sequences. -1 for random :param seq_per_set: Number of training sequences in each training set :param num_sets: Number of training set...
identifier_body
service.rs
pub fn new(address: message::Address, private_key: box_::SecretKey) -> MessageService { MessageService { address, private_key, precomputed_keys: HashMap::new(), message_handlers: HashMap::new(), } } } impl fmt::Debug for MessageService { fn fm...
} impl IsError for UnsupportedMessageType<'_> { fn error_id(&self) -> Id { Self::ERROR_ID } fn error_level(&self) -> Level { Self::ERROR_LEVEL } } impl fmt::Display for UnsupportedMessageType<'_> { fn fmt(&self, f: &mut fmt::Formatter) ...
{ UnsupportedMessageType { sender, message_type, } }
identifier_body
service.rs
type Result = Result<message::EncodedMessage, Error>; } impl actix::Handler<RegisterMessageHandler> for MessageService { type Result = actix::MessageResult<RegisterMessageHandler>; fn handle(&mut self, msg: RegisterMessageHandler, _: &mut Self::Context) -> Self::Result { self.message_handlers.insert(...
actix::MessageResult(Ok(req.0))
random_line_split
service.rs
#[derive(Clone)] pub struct RegisterMessageHandler { message_type: message::MessageType, handler: actix::Recipient<Request>, } impl RegisterMessageHandler { /// constructor pub fn new( message_type: message::MessageType, handler: actix::Recipient<Request>, ) -> RegisterMessageHandle...
fmt
identifier_name
tar_helper.rs
() .chain(std::iter::repeat(0)) .enumerate() .take(gnu_header.name.len()); // FIXME: could revert back to the slice copying code since we never change this for (i, b) in written { gnu_header.name[i] = b; } } ...
random_line_split
tar_helper.rs
is internal to `get` implementation. It uses some private parts of the `tar-rs` /// crate to append the headers and the contents to a pair of `bytes::Bytes` operated in a /// round-robin fashion. pub(super) struct TarHelper { bufsize: usize, bytes: BytesMut, header: Header, long_filename_header: Header...
} fn new_default_header() -> tar::Header { let mut header = tar::Header::new_gnu(); header.set_mtime(0); header.set_uid(0); header.set_gid(0); header } fn new_long_filename_header() -> tar::Header { let mut long_filename_header = tar::Header::new_gnu()...
{ let bytes = BytesMut::with_capacity(n); // these are 512 a piece let header = Self::new_default_header(); let long_filename_header = Self::new_long_filename_header(); let mut zeroes = BytesMut::with_capacity(512); for _ in 0..(512 / 8) { zeroes.put_u64(0); ...
identifier_body
tar_helper.rs
is internal to `get` implementation. It uses some private parts of the `tar-rs` /// crate to append the headers and the contents to a pair of `bytes::Bytes` operated in a /// round-robin fashion. pub(super) struct TarHelper { bufsize: usize, bytes: BytesMut, header: Header, long_filename_header: Header...
( &mut self, path: &Path, metadata: &Metadata, total_size: u64, ) -> Result<[Option<Bytes>; 3], GetError> { let mut ret: [Option<Bytes>; 3] = Default::default(); if let Err(e) = self.header.set_path(path) { let data = prepare_long_header(&...
apply_file
identifier_name
chip8.go
self.LoadGame("brix.c8") } //Read file in curent dir into Memory func (self *Chip8) LoadGame(filename string) { // rom, _ := ioutil.ReadFile(filename) filename = self.Games[self.GameIndex] fmt.Printf("Loading Game %s", filename) f, _ := asset.Open(filename) rom, _ := ioutil.ReadAll(f) rom_length := len(rom) ...
{ self.Pc = 0x200 // Program counter starts at 0x200, the Space of Memory after the interpreter self.Opcode = 0 // Reset current Opcode self.Index = 0 // Reset index register self.Sp = 0 // Reset stack pointer for x := 0; x < 16; x++ { self.V[x] = 0 } // for i := 0; i < 80; i++ { self.Memory[i] = Chi...
identifier_body
chip8.go
[0xF] = 0 } self.V[x] += self.V[y] self.Pc += 2 break case 0x0005: // 0x8XY5: VY is subtracted from VX. VF is set to 0 when there's a borrow, and 1 when there isn't y := self.Opcode & 0x00F0 >> 4 if self.V[y] > self.V[x] { self.V[0xF] = 0 //Borrow } else { self.V[0xF] = 1 } self.V[...
emory[self.Index+uint16(i)] = self.V[i] } self.Ind
conditional_block
chip8.go
Space of Memory after the interpreter self.Opcode = 0 // Reset current Opcode self.Index = 0 // Reset index register self.Sp = 0 // Reset stack pointer for x := 0; x < 16; x++ { self.V[x] = 0 } // for i := 0; i < 80; i++ { self.Memory[i] = Chip8_fontset[i] } // Clear display for i := 0; i < 64*32...
self.V[x] += NN self.Pc += 2 break //0X8000 - 8 CASES /* 8XY0 Sets VX to the value of VY. 8XY1 Sets VX to VX or VY. 8XY2 Sets VX to VX and VY. 8XY3 Sets VX to VX xor VY. 8XY4 Adds VY to VX. VF is set to 1 when there's a carry, and to 0 when there isn't. */ case 0x8000: switch self.Opcode...
self.Pc += 2 break case 0x7000: //0x7XNN Adds NN to VX. x := (self.Opcode & 0xF00) >> 8 NN := byte(self.Opcode & 0x00FF)
random_line_split
chip8.go
of Memory after the interpreter self.Opcode = 0 // Reset current Opcode self.Index = 0 // Reset index register self.Sp = 0 // Reset stack pointer for x := 0; x < 16; x++ { self.V[x] = 0 } // for i := 0; i < 80; i++ { self.Memory[i] = Chip8_fontset[i] } // Clear display for i := 0; i < 64*32; i++ ...
(filename string) { // rom, _ := ioutil.ReadFile(filename) filename = self.Games[self.GameIndex] fmt.Printf("Loading Game %s", filename) f, _ := asset.Open(filename) rom, _ := ioutil.ReadAll(f) rom_length := len(rom) if rom_length > 0 { // fmt.Printf("Rom Length = %d\n", rom_length) } //If room to store ROM...
LoadGame
identifier_name
final.go
minorSep)) } return strings.Join(strs, majorSep) } // Graph is the primary data structure for holding the highway data. The map's // key is the 'origin' Place, and the EdgeMap contains 'destination' Places // as keys and the travel distance and time as values. type Graph map[Place]EdgeMap // String returns a singl...
} } // Places provides a slice of unique Places in the graph. // Use `ByState` or `ByCity` with pkg `sort` to sort the slice. func (g Graph) Places() []Place { places := make([]Place, 0, len(g)) for k := range g { places = append(places, k) } return places } // Edge gets the Weight (edge data) for the connect...
{ fmt.Fprintf(w, "\t%-16s%3s%7.1fmi%10s\n", kk.City, kk.State, vv.Distance*MetersToMiles, vv.TravelTime) }
conditional_block
final.go
bool) { best := radius + 1 for p := range g { d := sphericalLawOfCos(lat, lon, p.Latitude, p.Longitude) if d <= radius && d < best { match = p dist = d found = true best = d } } if !found { return Place{}, 0, false } return } // used for sphericalLawOfCos() const ( earthradius = 6371e3 // ...
= p[j], p[i] }
identifier_body
final.go
minorSep)) } return strings.Join(strs, majorSep) } // Graph is the primary data structure for holding the highway data. The map's // key is the 'origin' Place, and the EdgeMap contains 'destination' Places // as keys and the travel distance and time as values. type Graph map[Place]EdgeMap // String returns a singl...
(origin Place, predicate MinMax, by Accessor) (most Place, ok bool) { dm, ok := g[origin] if !ok { return most, false } var cur *Weight for k, v := range dm { // start by setting the first value to the current best if cur == nil { most = k *cur = v continue } // get the mostest bestval := pr...
Most
identifier_name
final.go
the zero value and ok is false. func (g Graph) Edge(origin, destination Place) (data Weight, ok bool) { if dm, ok := g[origin]; ok { if data, ok := dm[destination]; ok { return data, true } } return } // // // // The following few types are used with Graph.Most() // // // // MinMax is a type of function th...
} return nodes }
random_line_split
nrml04.py
NRML04_LOWER_SEISMO_DEPTH = etree.QName(NRML04_NS,'lowerSeismoDepth') NRML04_MAG_SCALE_REL = etree.QName(NRML04_NS,'magScaleRel') NRML04_RUPT_ASPECT_RATIO = etree.QName(NRML04_NS,'ruptAspectRatio') NRML04_INCREMENTAL_MFD = etree.QName(NRML04_NS,'incrementalMFD') NRML04_TRUNCATED_GR = etree.QName(NRML04_NS,'truncGutenbe...
def _append_truncated_gr_mfd(element, mfd): """ Append NRML 0.4 truncated GR MFD. mfd is an instance of TruncatedGutenbergRichterMfdNrml03. """ attrib = {'aValue': str(mfd.a_val), 'bValue': str(mfd.b_val), 'minMag': str(mfd.min_mag), 'maxMag': str(mfd.max_m...
element.append(incremental_mfd)
random_line_split
nrml04.py
') NRML04_LOWER_SEISMO_DEPTH = etree.QName(NRML04_NS,'lowerSeismoDepth') NRML04_MAG_SCALE_REL = etree.QName(NRML04_NS,'magScaleRel') NRML04_RUPT_ASPECT_RATIO = etree.QName(NRML04_NS,'ruptAspectRatio') NRML04_INCREMENTAL_MFD = etree.QName(NRML04_NS,'incrementalMFD') NRML04_TRUNCATED_GR = etree.QName(NRML04_NS,'truncGute...
(element, mag_scale_rel): """ Append NRML 0.4 magnitude scaling relationship element. """ msr = etree.Element(NRML04_MAG_SCALE_REL) msr.text = mag_scale_rel element.append(msr) def _append_rupt_aspect_ratio(element, rupt_aspect_ratio): """ Append NRML 0.4 rupture aspect ratio. """ ...
_append_mag_scaling_rel
identifier_name
nrml04.py
') NRML04_LOWER_SEISMO_DEPTH = etree.QName(NRML04_NS,'lowerSeismoDepth') NRML04_MAG_SCALE_REL = etree.QName(NRML04_NS,'magScaleRel') NRML04_RUPT_ASPECT_RATIO = etree.QName(NRML04_NS,'ruptAspectRatio') NRML04_INCREMENTAL_MFD = etree.QName(NRML04_NS,'incrementalMFD') NRML04_TRUNCATED_GR = etree.QName(NRML04_NS,'truncGute...
def _append_id_name_tect_reg(element, NRML04_SOURCE, ID, name, tect_reg): """ Append id, name, tectonic region type for the given NRML 0.4 source typology. Returns the source element. """ attrib = {'id': ID, 'name': name, 'tectonicRegion': tect_reg} source = etree.Element(NRML04_SOURCE, a...
""" Append and return NRML 0.4 source model element. """ attrib = {'name': name} source_model = etree.Element(NRML04_SOURCE_MODEL,attrib=attrib) element.append(source_model) return source_model
identifier_body
nrml04.py
NRML04_LOWER_SEISMO_DEPTH = etree.QName(NRML04_NS,'lowerSeismoDepth') NRML04_MAG_SCALE_REL = etree.QName(NRML04_NS,'magScaleRel') NRML04_RUPT_ASPECT_RATIO = etree.QName(NRML04_NS,'ruptAspectRatio') NRML04_INCREMENTAL_MFD = etree.QName(NRML04_NS,'incrementalMFD') NRML04_TRUNCATED_GR = etree.QName(NRML04_NS,'truncGutenbe...
else: raise ValueError('MFD element nor recognized.') def _create_nrml(): """ Create and return NRML 0.4 root element. """ return etree.Element(NRML04_ROOT_TAG, nsmap=NSMAP) def _append_source_model(element, name): """ Append and return NRML 0.4 source model element. """ a...
min_mag = float(mfd.attrib['minMag']) bin_width = float(mfd.attrib['binWidth']) occur_rates = numpy.array(mfd.find(NRML04_OCCUR_RATES.text). text.split(), dtype=float) return IncrementalMfdNRML04(min_mag, bin_width, occur_rates)
conditional_block
code.go
in " + quotient + "\n" divcode += "\t\t\t; Safe remainder in " + remainder + "\n" if _, err := strconv.Atoi(divisor); err == nil { divcode += "\tmov rax, " + divisor + "\n" } else { divcode += "\tmov rax, [" + divisor + "]\n" } if _, err := strconv.Atoi(dividend); err == nil { divcode += "\tmov rbx, " + d...
// This is the code snipped checking the condition inside an assembly loop.
random_line_split
code.go
, [var2] mov [var3], eax */ // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+// // Mathsnippets The following code templates are appended to the // output program to do ugly numbercrunshing work The following // functions' parameters are names of variables inside the output //...
pc.appendCode(code) } // createCall allows the label passed as string argument to be // called. //"call" executes a function inside assembly. It cleanes used // registers before and after the function did its job. -> amd64 Sys V // abi // FIXME: 'jmp vs. call'? func (pc *programCode) createCall(name string) { code...
{ if _, err := strconv.Atoi(argSlice[i]); err == nil { code += "\tmov " + registerSlice[i] + argSlice[i] + "\n" } else { code += "\tmov " + registerSlice[i] + "[" + argSlice[i] + "]\n" } }
conditional_block
code.go
, [var2] mov [var3], eax */ // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+// // Mathsnippets The following code templates are appended to the // output program to do ugly numbercrunshing work The following // functions' parameters are names of variables inside the output //...
(name string) { code := "" code += "\n" + name + ":\n" pc.funcSlice = append(pc.funcSlice, name) pc.indentLevel += 1 // dive deeper -> next buffer. // Please have a look to FIXME: Where can I find what? pc.appendCode(code) } // createReturn leaves the innermost function/indent buffer by // decrementing the pc.i...
createLabel
identifier_name
code.go
/* mov eax, [var1] add eax, [var2] mov [var3], eax */ // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+// // Mathsnippets The following code templates are appended to the // output program to do ugly numbercrunshing work The following // functions' parameters are names of va...
{ len := (int64)(len(pc.stringMap[sname])) - 2 // FIXME: WTF int64. Why not use int and strconv.Atoi(var string) // and stringcon.Itoa(var int) strlen := strconv.FormatInt(len, 10) code := "\tmov rax, 1\t;print String" + sname + "\n\tmov rdi, 1\n\tmov rdx, " + strlen + "\n\tmov rsi, " + sname + "\n\tsyscall\n" ...
identifier_body
root.rs
pub hpre: u32, pub prediv: u32, } #[allow(unused_labels)] #[inline(never)] pub fn handler(reg: Regs, thr_init: ThrsInit) { let mut clock_mode = ClockMode::High64MHz; let (thr, scb) = thr::init_extended(thr_init); thr.hard_fault.add_once(|| panic!("Hard Fault")); // Allocate the clock control ...
( res: &SystemRes, thr: &Thrs, exti5: &ExtiDrv<Exti5, thr::Exti95>, gpio_pins: &GpioPins, hclk: u32, ) -> Event { println!("Enter listen, hclk={}", hclk); // Attach a listener that will notify us on user button pressed. let mut button_stream = exti5.create_saturating_stream(); // At...
listen
identifier_name
root.rs
4 // 1101: SYSCLK divided by 128 // 1110: SYSCLK divided by 256 // 1111: SYSCLK divided by 512 hpre: 0b0000, // Field RCC_CFGR HPRE in ref. manual RM0316. // PREDIV division factor. prediv: 0b000, // Field RCC_CFGR2 PREDIV in ref. manual RM0316. }; swo::flush();...
{ doubleclick_protection = 0; println!("++"); }
conditional_block
root.rs
pub hpre: u32, pub prediv: u32, } #[allow(unused_labels)] #[inline(never)] pub fn handler(reg: Regs, thr_init: ThrsInit) { let mut clock_mode = ClockMode::High64MHz; let (thr, scb) = thr::init_extended(thr_init); thr.hard_fault.add_once(|| panic!("Hard Fault")); // Allocate the clock control ...
'user_button_pressed: loop { // Reset the clock control registers to their default. System::reset_rcc(&res); // Apply the current clock tree configuration. System::apply_clock_config(&res); // Calculate the configured clock speed. let hclk = System::calculate_hclk(...
falling: false, // trigger the interrupt on a falling edge. rising: true, // don't trigger the interrupt on a rising edge. });
random_line_split
wait_cell.rs
<'a> { /// The [`WaitCell`] being waited on. cell: &'a WaitCell, } #[derive(Eq, PartialEq, Copy, Clone)] struct State(usize); // === impl WaitCell === impl WaitCell { loom_const_fn! { /// Returns a new `WaitCell`, with no [`Waker`] stored in it. #[must_use] pub fn new() -> Self { ...
Subscribe
identifier_name
wait_cell.rs
Subscribe to notifications from the cell *before* calling /// // `do_something_that_causes_a_wakeup()`, to ensure that we are /// // ready to be woken when the interrupt is unmasked. /// let wait = WAIT_CELL.subscribe().await; /// /// // Actually perform the operation. /// do_something_that_cau...
{ if *self == Self::WAITING { return f.write_str("WAITING"); } f.debug_tuple("UnknownState") .field(&format_args!("{:#b}", self.0)) .finish()?; }
conditional_block
wait_cell.rs
and when the /// future is first polled, the future will *not* complete. If the caller is /// responsible for performing an operation which will result in an eventual /// wakeup, prefer calling [`subscribe`] _before_ performing that operation /// and `.await`ing the [`Wait`] future returned by [`subscr...
random_line_split