Python get cloud

60 Python code examples are found related to " get cloud". You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: preprocess.py    From cloudml-edge-automation with Apache License 2.0 6 votes vote down vote up
def get_cloud_project():
  cmd = [
      'gcloud', '-q', 'config', 'list', 'project',
      '--format=value(core.project)'
  ]
  with open(os.devnull, 'w') as dev_null:
    try:
      res = subprocess.check_output(cmd, stderr=dev_null).strip()
      if not res:
        raise Exception('--cloud specified but no Google Cloud Platform '
                        'project found.\n'
                        'Please specify your project name with the --project '
                        'flag or set a default project: '
                        'gcloud config set project YOUR_PROJECT_NAME')
      return res
    except OSError as e:
      if e.errno == errno.ENOENT:
        raise Exception('gcloud is not installed. The Google Cloud SDK is '
                        'necessary to communicate with the Cloud ML service. '
                        'Please install and set up gcloud.')
      raise 
Example 2
Source File: azure_cloud.py    From msrestazure-for-python with MIT License 6 votes vote down vote up
def get_cloud_from_metadata_endpoint(arm_endpoint, name=None, session=None):
    """Get a Cloud object from an ARM endpoint.

    .. versionadded:: 0.4.11

    :Example:

    .. code:: python

        get_cloud_from_metadata_endpoint(https://management.azure.com/, "Public Azure")

    :param str arm_endpoint: The ARM management endpoint
    :param str name: An optional name for the Cloud object. Otherwise it's the ARM endpoint
    :params requests.Session session: A requests session object if you need to configure proxy, cert, etc.
    :rtype Cloud:
    :returns: a Cloud object
    :raises: MetadataEndpointError if unable to build the Cloud object
    """
    cloud = Cloud(name or arm_endpoint)
    cloud.endpoints.management = arm_endpoint
    cloud.endpoints.resource_manager = arm_endpoint
    _populate_from_metadata_endpoint(cloud, arm_endpoint, session)
    return cloud 
Example 3
Source File: __init__.py    From openstacksdk with Apache License 2.0 6 votes vote down vote up
def get_cloud_region(
        service_key=None, options=None,
        app_name=None, app_version=None,
        load_yaml_config=True,
        load_envvars=True,
        **kwargs):
    config = OpenStackConfig(
        load_yaml_config=load_yaml_config,
        load_envvars=load_envvars,
        app_name=app_name, app_version=app_version)
    if options:
        config.register_argparse_arguments(options, sys.argv, service_key)
        parsed_options = options.parse_known_args(sys.argv)
    else:
        parsed_options = None

    return config.get_one(options=parsed_options, **kwargs) 
Example 4
Source File: landsat_functions.py    From CrisisMappingToolkit with Apache License 2.0 6 votes vote down vote up
def getCloudPercentage(image, region):
    '''Estimates the cloud cover percentage in a Landsat image'''
    
    # The function will attempt the calculation in these ranges
    # - Native Landsat resolution is 30
    MIN_RESOLUTION = 60
    MAX_RESOLUTION = 1000
    
    resolution = MIN_RESOLUTION
    while True:
        try:
            oneMask     = ee.Image(1.0)
            cloudScore  = detect_clouds(image)
            areaCount   = oneMask.reduceRegion(  ee.Reducer.sum(),  region, resolution)
            cloudCount  = cloudScore.reduceRegion(ee.Reducer.sum(), region, resolution)
            percentage  = safe_get_info(cloudCount)['constant'] / safe_get_info(areaCount)['constant']
            return percentage
        except Exception as e:
            # Keep trying with lower resolution until we succeed
            resolution = 2*resolution
            if resolution > MAX_RESOLUTION:
                raise e 
Example 5
Source File: image.py    From mx-DeepIM with Apache License 2.0 6 votes vote down vote up
def get_point_cloud_fast(config, valid_pc_list, sample_number, phase="train"):
    # type: (object, object, object) -> object
    X_obj_tensor = []
    X_obj_weights_tensor = []
    for idx, raw_pc in enumerate(valid_pc_list):
        number_proposals = raw_pc.shape[1]
        num_kept = min(sample_number, number_proposals)
        keep_idx = np.arange(number_proposals)
        np.random.shuffle(keep_idx)
        keep_idx = keep_idx[:num_kept]
        X_obj = np.zeros((1, 3, sample_number))
        X_obj[0, :, :num_kept] = np.array([c[keep_idx] for c in raw_pc])
        X_obj_tensor.append(X_obj)
        channel_num = 3
        X_obj_weights = np.zeros((1, channel_num, sample_number))
        X_obj_weights[0, :, :num_kept] = 1
        X_obj_weights_tensor.append(X_obj_weights)
    return X_obj_tensor, X_obj_weights_tensor 
Example 6
Source File: ATLASSiteInformation.py    From pilot with Apache License 2.0 6 votes vote down vote up
def getCorrespondingCloud(self, ddm):
        """ Find the cloud where ddm exists """

        cloud = ""

        # Scan the enture unlimited set of queuedata previously downloaded
        # Load the dictionary
        dictionary = self.getFullQueuedataDictionary()
        if dictionary != {}:
            for queuename in dictionary.keys():
                if ddm in dictionary[queuename]['ddm']:
                    cloud = dictionary[queuename]['cloud']
                    tolog("Found cloud=%s for ddm=%s at queuename=%s" % (cloud, ddm, queuename))
                    break

        return cloud 
Example 7
Source File: arcus_alarm.py    From hubblemon with Apache License 2.0 6 votes vote down vote up
def get_cloud_of_node(self, name, port):
		try:
			ip = socket.gethostbyname(name)
		except Exception as e:
			print(e)
			print('# exception: %s' % name)
			return None

		key = ip + ':' + port
		if key not in self.node_cloud_map:
			# retry with ip:0 # implicit define
			key = ip + ':0'
			if key not in self.node_cloud_map:
				return None

		return self.node_cloud_map[key] 
Example 8
Source File: s3dis_provider.py    From pointwise with MIT License 6 votes vote down vote up
def get_batch_point_cloud(self):
        start_idx = self.cur_batch * self.batch_size
        end_idx = (self.cur_batch + 1) * self.batch_size

        points_data = self.current_data[start_idx:end_idx, :, :]
        label_data = self.current_label[start_idx:end_idx, :]

        if self.sort_cloud:
            points_data, label_data = util.sort_point_cloud_xyz2(points_data, label_data)

        self.batch_points[:, :, :] = points_data[:, :, 0:3]
        self.batch_input[:] = points_data[:]
        self.batch_label[:] = label_data[:]

        #cloud = pe.PointCloud(self.batch_points[0, :, :].astype('float32'))
        #pe.Visualizer.show(cloud)

        return self.batch_points, self.batch_input, self.batch_label 
Example 9
Source File: v3utils_api.py    From whoville with Apache License 2.0 6 votes vote down vote up
def get_cloud_storage_matrix_v3(self, **kwargs):
        """
        returns supported cloud storage for stack version
        Define stack version at least at patch level eg. 2.6.0
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please define a `callback` function
        to be invoked when receiving the response.
        >>> def callback_function(response):
        >>>     pprint(response)
        >>>
        >>> thread = api.get_cloud_storage_matrix_v3(callback=callback_function)

        :param callback function: The callback function
            for asynchronous request. (optional)
        :param str stack_version:
        :return: list[CloudStorageSupportedResponse]
                 If the method is called asynchronously,
                 returns the request thread.
        """
        kwargs['_return_http_data_only'] = True
        if kwargs.get('callback'):
            return self.get_cloud_storage_matrix_v3_with_http_info(**kwargs)
        else:
            (data) = self.get_cloud_storage_matrix_v3_with_http_info(**kwargs)
            return data 
Example 10
Source File: cameraview.py    From director with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def getStereoPointCloud(decimation=4, imagesChannel='MULTISENSE_CAMERA', cameraName='MULTISENSE_CAMERA_LEFT', removeSize=0, rangeThreshold = -1):

    q = imageManager.queue

    utime = q.getCurrentImageTime(cameraName)
    if utime == 0:
        return None

    p = vtk.vtkPolyData()
    cameraToLocal = vtk.vtkTransform()

    q.getPointCloudFromImages(imagesChannel, p, decimation, removeSize, rangeThreshold)

    if (p.GetNumberOfPoints() > 0):
      q.getTransform(cameraName, 'local', utime, cameraToLocal)
      p = filterUtils.transformPolyData(p, cameraToLocal)

    return p 
Example 11
Source File: v1util_api.py    From whoville with Apache License 2.0 6 votes vote down vote up
def get_cloud_storage_matrix(self, **kwargs):
        """
        returns supported cloud storage for stack version
        Define stack version at least at patch level eg. 2.6.0
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please define a `callback` function
        to be invoked when receiving the response.
        >>> def callback_function(response):
        >>>     pprint(response)
        >>>
        >>> thread = api.get_cloud_storage_matrix(callback=callback_function)

        :param callback function: The callback function
            for asynchronous request. (optional)
        :param str stack_version:
        :return: list[CloudStorageSupportedResponse]
                 If the method is called asynchronously,
                 returns the request thread.
        """
        kwargs['_return_http_data_only'] = True
        if kwargs.get('callback'):
            return self.get_cloud_storage_matrix_with_http_info(**kwargs)
        else:
            (data) = self.get_cloud_storage_matrix_with_http_info(**kwargs)
            return data 
Example 12
Source File: utils.py    From eccv18-rgb_pose_refinement with MIT License 6 votes vote down vote up
def get_viewpoint_cloud(depth, cam, num_keep):
    """ Extract 3d points from depth map and intrinsics
    :param depth:
    :param cam:
    :return: Numpy array of 3D points (N, 3)
    """
    dep_c = depth.copy()
    cloud = backproject(depth, cam)
    contours_from_dep = extract_contour(depth)

    dep_c[contours_from_dep == 0] = 0
    mask = np.stack((dep_c, dep_c, dep_c), axis=2) > 0
    contours = np.reshape(cloud[mask], (-1, 3))
    contours = contours[np.random.choice(
        contours.shape[0], num_keep)]

    return contours 
Example 13
Source File: userdatamodel_project.py    From fence with Apache License 2.0 6 votes vote down vote up
def get_cloud_providers_from_project(current_session, project_id):
    """
    Retrieve cloud provider to be used in other operations that require the
    backend.
    """
    accesses = current_session.query(StorageAccess).filter(
        StorageAccess.project_id == project_id
    )
    cloud_providers = []
    for access in accesses:
        cloud_providers.append(
            current_session.query(CloudProvider)
            .filter(CloudProvider.id == access.provider_id)
            .first()
        )
    return cloud_providers 
Example 14
Source File: obj_utils.py    From monopsr with MIT License 6 votes vote down vote up
def get_lidar_point_cloud(sample_name, frame_calib, velo_dir):
    """Gets the lidar point cloud in cam0 frame.

    Args:
        sample_name: Sample name
        frame_calib: FrameCalib
        velo_dir: Velodyne directory

    Returns:
        (3, N) point_cloud in the form [[x,...][y,...][z,...]]
    """

    xyzi = read_lidar(velo_dir, sample_name)

    # Calculate the point cloud
    points_in_lidar_frame = xyzi[:, 0:3]
    points = calib_utils.lidar_to_cam_frame(points_in_lidar_frame, frame_calib)

    return points.T 
Example 15
Source File: demo_utils.py    From monopsr with MIT License 6 votes vote down vote up
def get_point_cloud(pc_source, sample_name, frame_calib,
                    velo_dir=None, depth_dir=None, disp_dir=None,
                    image_shape=None, cam_idx=2):

    if pc_source == 'lidar':
        point_cloud = obj_utils.get_lidar_point_cloud_for_cam(
            sample_name, frame_calib, velo_dir, image_shape, cam_idx)
    elif pc_source == 'depth':
        point_cloud = obj_utils.get_depth_map_point_cloud(
            sample_name, frame_calib, depth_dir)
    elif pc_source == 'stereo':
        raise NotImplementedError('Not implemented yet')
    else:
        raise ValueError('Invalid point cloud source', pc_source)

    return point_cloud 
Example 16
Source File: plextv.py    From Tautulli with GNU General Public License v3.0 6 votes vote down vote up
def get_cloud_server_status(self):
        cloud_status = self.cloud_server_status(output_format='xml')

        try:
            status_info = cloud_status.getElementsByTagName('info')
        except Exception as e:
            logger.warn("Tautulli PlexTV :: Unable to parse XML for get_cloud_server_status: %s." % e)
            return False

        for info in status_info:
            servers = info.getElementsByTagName('server')
            for s in servers:
                if helpers.get_xml_attr(s, 'address') == plexpy.CONFIG.PMS_IP:
                    if helpers.get_xml_attr(info, 'running') == '1':
                        return True
                    else:
                        return False 
Example 17
Source File: fusion.py    From tsdf-fusion-python with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def get_point_cloud(self):
    """Extract a point cloud from the voxel volume.
    """
    tsdf_vol, color_vol = self.get_volume()

    # Marching cubes
    verts = measure.marching_cubes_lewiner(tsdf_vol, level=0)[0]
    verts_ind = np.round(verts).astype(int)
    verts = verts*self._voxel_size + self._vol_origin

    # Get vertex colors
    rgb_vals = color_vol[verts_ind[:, 0], verts_ind[:, 1], verts_ind[:, 2]]
    colors_b = np.floor(rgb_vals / self._color_const)
    colors_g = np.floor((rgb_vals - colors_b*self._color_const) / 256)
    colors_r = rgb_vals - colors_b*self._color_const - colors_g*256
    colors = np.floor(np.asarray([colors_r, colors_g, colors_b])).T
    colors = colors.astype(np.uint8)

    pc = np.hstack([verts, colors])
    return pc 
Example 18
Source File: cloud_storage.py    From Jandroid with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def GetErrorObjectForCloudStorageStderr(stderr):
  if (stderr.startswith((
      'You are attempting to access protected data with no configured',
      'Failure: No handler was ready to authenticate.')) or
      re.match('.*401.*does not have .* access to .*', stderr)):
    return CredentialsError()
  if ('status=403' in stderr or 'status 403' in stderr or
      '403 Forbidden' in stderr or
      re.match('.*403.*does not have .* access to .*', stderr)):
    return PermissionError()
  if (stderr.startswith('InvalidUriError') or 'No such object' in stderr or
      'No URLs matched' in stderr or 'One or more URLs matched no' in stderr):
    return NotFoundError(stderr)
  if '500 Internal Server Error' in stderr:
    return ServerError(stderr)
  return CloudStorageError(stderr) 
Example 19
Source File: helpers.py    From pytos with Apache License 2.0 6 votes vote down vote up
def get_cloud_console_servers(self, vendor, search_string):
        """ Get the list of cloud network objects in SecureApp .

        :return: The list of cloud network objects in SecureApp.
        :rtype: VM_Instances
        :raise IOError: If there was a communication error.
        """
        logger.info("Getting cloud network objects for SecureApp.")
        uri = "/securechangeworkflow/api/secureapp/cloud_console/servers?vendor={}&search_string={}".format(vendor,
                                                                                                            search_string)
        try:
            response_string = self.get_uri(uri, expected_status_codes=200).response.content
        except RequestException:
            message = "Failed to get cloud console servers for SecureApp."
            logger.critical(message)
            raise IOError(message)
        try:
            cloud_console_servers = VM_Instances.from_xml_string(response_string)
        except (ValueError, AttributeError):
            message = "Failed to get cloud console servers for SecureApp."
            logger.critical(message)
            raise ValueError(message)
        return cloud_console_servers 
Example 20
Source File: compose_preseed.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_cloud_init_legacy_apt_config_to_inject_key_to_archive(node):
    arch = node.split_arch()[0]
    archive = PackageRepository.objects.get_default_archive(arch)
    apt_sources = {}
    apt_sources["apt_sources"] = []

    if archive.key:
        apt_sources["apt_sources"].append(
            {
                "key": archive.key,
                "source": "deb %s $RELEASE main" % (archive.url),
                "filename": "lp1743966.list",
            }
        )

    return apt_sources 
Example 21
Source File: juju.py    From conjure-up with MIT License 6 votes vote down vote up
def get_cloud_types_by_name():
    """ Return a mapping of cloud names to their type.

    This accounts for some normalizations that get_clouds() doesn't.
    """
    clouds = {n: c['type'] for n, c in get_clouds().items()}

    # normalize 'lxd' cloud type to localhost; 'lxd' can happen
    # depending on how the controller was bootstrapped
    for name, cloud_type in clouds.items():
        if cloud_type == 'lxd':
            clouds[name] = 'localhost'

    for provider in consts.CUSTOM_PROVIDERS:
        if provider not in clouds:
            clouds[provider] = provider

    return clouds 
Example 22
Source File: deployment_main.py    From BaoTa-Panel with GNU General Public License v3.0 6 votes vote down vote up
def GetCloudList(self,get):
        try:
            import web
            if not hasattr(web.ctx.session,'package'):
                downloadUrl = public.get_url() + '/install/lib/plugin/deployment/package.json';
                tmp = json.loads(public.httpGet(downloadUrl));
                if not tmp: return public.returnMsg(False,'从云端获取失败!');
                jsonFile = self.__setupPath + '/list.json';
                public.writeFile(jsonFile,json.dumps(tmp));
                
                downloadUrl = public.get_url() + '/install/lib/plugin/deployment/type.json';
                tmp = json.loads(public.httpGet(downloadUrl));
                if not tmp: return public.returnMsg(False,'从云端获取失败!');
                jsonFile = self.__setupPath + '/type.json';
                public.writeFile(jsonFile,json.dumps(tmp));
                
                web.ctx.session.package = True
                return public.returnMsg(True,'更新成功!');
            return public.returnMsg(True,'无需更新!');
        except:
            return public.returnMsg(False,'从云端获取失败!');
        
        
    
    #添加程序包 
Example 23
Source File: S2PixelCloudDetector.py    From sentinel2-cloud-detector with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
def get_cloud_masks(self, X, **kwargs):
        """
        Runs the cloud detection on the input images (dimension n_images x n x m x 10
        or n_images x n x m x 13) and returns the raster cloud mask (dimension n_images x n x m).
        Pixel values equal to 0 indicate pixels classified as clear-sky, while values
        equal to 1 indicate pixels classified as clouds.

        :param X: input Sentinel-2 image obtained with Sentinel-Hub's WMS/WCS request
                  (see https://github.com/sentinel-hub/sentinelhub-py)
        :type X: numpy array (shape n_images x n x m x 10 or n x m x 13)
        :param kwargs: Any keyword arguments that will be passed to the classifier's prediction method
        :return: raster cloud mask
        :rtype: numpy array (shape n_images x n x m)
        """

        cloud_probs = self.get_cloud_probability_maps(X, **kwargs)

        return self.get_mask_from_prob(cloud_probs) 
Example 24
Source File: S2PixelCloudDetector.py    From sentinel2-cloud-detector with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
def get_cloud_probability_maps(self, X, **kwargs):
        """
        Runs the cloud detection on the input images (dimension n_images x n x m x 10
        or n_images x n x m x 13) and returns an array of cloud probability maps (dimension
        n_images x n x m). Pixel values close to 0 indicate clear-sky-like pixels, while
        values close to 1 indicate pixels covered with clouds.

        :param X: input Sentinel-2 image obtained with Sentinel-Hub's WMS/WCS request
                  (see https://github.com/sentinel-hub/sentinelhub-py)
        :type X: numpy array (shape n_images x n x m x 10 or n x m x 13)
        :param kwargs: Any keyword arguments that will be passed to the classifier's prediction method
        :return: cloud probability map
        :rtype: numpy array (shape n_images x n x m)
        """
        band_num = X.shape[-1]
        exp_bands = 13 if self.all_bands else len(self.BAND_IDXS)
        if band_num != exp_bands:
            raise ValueError("Parameter 'all_bands' is set to {}. Therefore expected band data with {} bands, "
                             "got {} bands".format(self.all_bands, exp_bands, band_num))

        if self.all_bands:
            X = X[..., self.BAND_IDXS]

        return self.classifier.image_predict_proba(X, **kwargs)[..., 1] 
Example 25
Source File: panelPlugin.py    From BaoTa-Panel with GNU General Public License v3.0 6 votes vote down vote up
def GetCloudWarning(self,get):
        import json
        if not hasattr(web.ctx.session,'downloadUrl'): web.ctx.session.downloadUrl = 'http://download.bt.cn';
        downloadUrl = web.ctx.session.downloadUrl + '/install/warning.json'
        tstr = public.httpGet(downloadUrl)
        data = json.loads(tstr);
        if not data: return False;
        wfile = 'data/warning.json';
        wlist = json.loads(public.readFile(wfile));
        for i in range(len(data['data'])):
            for w in wlist['data']:
                if data['data'][i]['name'] != w['name']: continue;
                data['data'][i]['ignore_count'] = w['ignore_count'];
                data['data'][i]['ignore_time'] = w['ignore_time'];                         
        public.writeFile(wfile,json.dumps(data));
        return data;

    
    #请求插件事件 
Example 26
Source File: ehpc_20180412.py    From alibabacloud-python-sdk-v2 with Apache License 2.0 6 votes vote down vote up
def get_cloud_metric_logs(
            self,
            aggregation_type=None,
            filter_=None,
            metric_categories=None,
            metric_scope=None,
            from_=None,
            cluster_id=None,
            to=None,
            aggregation_interval=None,
            reverse=None):
        api_request = APIRequest('GetCloudMetricLogs', 'GET', 'http', 'RPC', 'query')
        api_request._params = {
            "AggregationType": aggregation_type,
            "Filter": filter_,
            "MetricCategories": metric_categories,
            "MetricScope": metric_scope,
            "From": from_,
            "ClusterId": cluster_id,
            "To": to,
            "AggregationInterval": aggregation_interval,
            "Reverse": reverse}
        return self._handle_request(api_request).result 
Example 27
Source File: pymasker.py    From pymasker with MIT License 6 votes vote down vote up
def get_cloud_mask(self, conf=None, cumulative=False):
        '''Generate a cloud mask.

        Parameters
            conf		-	Level of confidence that cloud exists.
            cumulative	-	A Boolean value indicating whether to get masker with confidence value larger than the given one..

        Return
            mask 		-	A two-dimension binary mask.
        '''

        if self.collection == 0:
            if conf is None or conf == -1:
                raise Exception('Confidence value is required for creating cloud mask from pre-collection data.')

            return self.__get_mask(14, 3, conf, cumulative).astype(int)
        elif self.collection == 1 and (conf is None or conf == -1):
            return self.__get_mask(4, 1, 1, False).astype(int)
        elif self.collection == 1:
            return self.__get_mask(5, 3, conf, cumulative).astype(int) 
Example 28
Source File: cameraview.py    From director with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def getStereoPointCloudElapsed(self,decimation=4, imagesChannel='MULTISENSE_CAMERA', cameraName='MULTISENSE_CAMERA_LEFT', removeSize=0):
        q = imageManager.queue

        utime = q.getCurrentImageTime(cameraName)
        if utime == 0:
            return None, None, None

        if (utime - self.lastUtime < 1E6):
            return None, None, None

        p = vtk.vtkPolyData()
        cameraToLocalFused = vtk.vtkTransform()
        q.getTransform('MULTISENSE_CAMERA_LEFT_ALT', 'local', utime, cameraToLocalFused)
        cameraToLocal = vtk.vtkTransform()
        q.getTransform('MULTISENSE_CAMERA_LEFT', 'local', utime, cameraToLocal)
        prevToCurrentCameraTransform = vtk.vtkTransform()
        prevToCurrentCameraTransform.PostMultiply()
        prevToCurrentCameraTransform.Concatenate( cameraToLocal )
        prevToCurrentCameraTransform.Concatenate( self.lastCameraToLocal.GetLinearInverse() )
        distTravelled = np.linalg.norm( prevToCurrentCameraTransform.GetPosition() )

        # 0.2 heavy overlap
        # 0.5 quite a bit of overlap
        # 1.0 is good
        if (distTravelled  < 0.2 ):
            return None, None, None

        q.getPointCloudFromImages(imagesChannel, p, decimation, removeSize, removeThreshold = -1)

        self.lastCameraToLocal = cameraToLocal
        self.lastUtime = utime
        return p, cameraToLocalFused, cameraToLocal 
Example 29
Source File: ses_mail_notifier.py    From exporters with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_scrapy_cloud_link(jobkey):
    if not jobkey:
        return ''
    proj_id, remainder = jobkey.split('/', 1)
    return 'https://dash.scrapinghub.com/p/%s/job/%s' % (proj_id, remainder) 
Example 30
Source File: util.py    From fully-convolutional-point-network with MIT License 5 votes vote down vote up
def get_point_cloud_min_max_size(points):
    """ Get the minimum, maximum and size of the space occupied by points.

    Args:
    points: np.array
    
    Returns: np.array, np.array, np.array

    """

    points_min = np.amin(points, axis=0)
    points_max = np.amax(points, axis=0)
    points_size = points_max - points_min

    return points_min, points_max, points_size 
Example 31
Source File: robotsim.py    From pyOptimalMotionPlanning with Apache License 2.0 5 votes vote down vote up
def getPointCloud(self):
        """
        getPointCloud(Geometry3D self) -> PointCloud

        PointCloud
        Geometry3D::getPointCloud()

        Returns a PointCloud if this geometry is of type PointCloud. 
        """
        return _robotsim.Geometry3D_getPointCloud(self) 
Example 32
Source File: source.py    From script.module.clouddrive.common with GNU General Public License v3.0 5 votes vote down vote up
def get_cloud_drive_addons(self):
        addons = []
        response = KodiUtils.execute_json_rpc('Addons.GetAddons', {'type':'xbmc.python.pluginsource', 'enabled': True, 'properties': ['dependencies', 'name']})
        for addon in Utils.get_safe_value(Utils.get_safe_value(response, 'result', {}), 'addons', []):
            for dependency in addon['dependencies']:
                if dependency['addonid'] == self._addonid:
                    addons.append(addon)
                    break
        return addons 
Example 33
Source File: TextCommandParser.py    From UniqueBible with GNU General Public License v3.0 5 votes vote down vote up
def getCommentaryCloudID(self, commentary):
        cloudIDs = {
            "Barnes": "13uxButnFH2NRUV-YuyRZYCeh1GzWqO5J",
            "Benson": "1MSRUHGDilogk7_iZHVH5GWkPyf8edgjr",
            "BI": "1DUATP_0M7SwBqsjf20YvUDblg3_sOt2F",
            "Brooks": "1pZNRYE6LqnmfjUem4Wb_U9mZ7doREYUm",
            "Calvin": "1FUZGK9n54aXvqMAi3-2OZDtRSz9iZh-j",
            "CBSC": "1IxbscuAMZg6gQIjzMlVkLtJNDQ7IzTh6",
            "CECNT": "1MpBx7z6xyJYISpW_7Dq-Uwv0rP8_Mi-r",
            "CGrk": "1Jf51O0R911Il0V_SlacLQDNPaRjumsbD",
            "CHP": "1dygf2mz6KN_ryDziNJEu47-OhH8jK_ff",
            "Clarke": "1ZVpLAnlSmBaT10e5O7pljfziLUpyU4Dq",
            "CPBST": "14zueTf0ioI-AKRo_8GK8PDRKael_kB1U",
            "EBC": "1UA3tdZtIKQEx-xmXtM_SO1k8S8DKYm6r",
            "ECER": "1sCJc5xuxqDDlmgSn2SFWTRbXnHSKXeh_",
            "EGNT": "1ZvbWnuy2wwllt-s56FUfB2bS2_rZoiPx",
            "GCT": "1vK53UO2rggdcfcDjH6mWXAdYti4UbzUt",
            "Gill": "1O5jnHLsmoobkCypy9zJC-Sw_Ob-3pQ2t",
            "Henry": "1m-8cM8uZPN-fLVcC-a9mhL3VXoYJ5Ku9",
            "HH": "1RwKN1igd1RbN7phiJDiLPhqLXdgOR0Ms",
            "ICCNT": "1QxrzeeZYc0-GNwqwdDe91H4j1hGSOG6t",
            "JFB": "1NT02QxoLeY3Cj0uA_5142P5s64RkRlpO",
            "KD": "1rFFDrdDMjImEwXkHkbh7-vX3g4kKUuGV",
            "Lange": "1_PrTT71aQN5LJhbwabx-kjrA0vg-nvYY",
            "MacL": "1p32F9MmQ2wigtUMdCU-biSrRZWrFLWJR",
            "PHC": "1xTkY_YFyasN7Ks9me3uED1HpQnuYI8BW",
            "Pulpit": "1briSh0oDhUX7QnW1g9oM3c4VWiThkWBG",
            "Rob": "17VfPe4wsnEzSbxL5Madcyi_ubu3iYVkx",
            "Spur": "1OVsqgHVAc_9wJBCcz6PjsNK5v9GfeNwp",
            "Vincent": "1ZZNnCo5cSfUzjdEaEvZ8TcbYa4OKUsox",
            "Wesley": "1rerXER1ZDn4e1uuavgFDaPDYus1V-tS5",
            "Whedon": "1FPJUJOKodFKG8wsNAvcLLc75QbM5WO-9",
        }
        if commentary in cloudIDs:
            return cloudIDs[commentary]
        else:
            return "" 
Example 34
Source File: image.py    From mx-DeepIM with Apache License 2.0 5 votes vote down vote up
def get_point_cloud_model(config, pairdb):
    if pairdb[0]["gt_class"] not in point_cloud_dict:
        if not config.dataset.dataset.startswith("ModelNet"):
            point_path = os.path.join(config.dataset.model_dir, pairdb[0]["gt_class"], "points.xyz")
            point_cloud_dict[pairdb[0]["gt_class"]] = load_object_points(point_path)
        else:
            obj_path = os.path.join(config.dataset.model_dir, pairdb[0]["gt_class"] + ".obj")
            point_cloud_dict[pairdb[0]["gt_class"]] = load_points_from_obj(obj_path)

    points_obj = point_cloud_dict[pairdb[0]["gt_class"]]
    num_points = points_obj.shape[0]
    num_sample = config.train_iter.NUM_3D_SAMPLE
    num_keep = min(num_points, num_sample)

    keep_idx = np.arange(num_points)
    np.random.shuffle(keep_idx)
    keep_idx = keep_idx[:num_keep]

    points_sample = np.zeros((num_sample, 3))
    points_sample[:num_keep, :] = points_obj[keep_idx, :]

    channel_num = 3
    points_weights = np.zeros((num_sample, channel_num))
    points_weights[:num_keep, :] = 1
    points_sample = np.expand_dims(points_sample.T, axis=0)
    points_weights = np.expand_dims(points_weights.T, axis=0)
    return [points_sample], [points_weights] 
Example 35
Source File: panelPlugin.py    From BaoTa-Panel with GNU General Public License v3.0 5 votes vote down vote up
def getCloudPHPExt(self,get):
        import json
        try:
            if not hasattr(web.ctx.session,'downloadUrl'): web.ctx.session.downloadUrl = 'http://download.bt.cn';
            downloadUrl = web.ctx.session.downloadUrl + '/install/lib/phplib.json'
            tstr = public.httpGet(downloadUrl)
            data = json.loads(tstr);
            if not data: return False;
            public.writeFile('data/phplib.conf',json.dumps(data));
            return True;
        except:
            return False;
        
    #获取警告列表 
Example 36
Source File: image.py    From mx-DeepIM with Apache License 2.0 5 votes vote down vote up
def get_point_cloud_observed(config, points_model, pose_observed):
    R = pose_observed[:, :3]
    T = pose_observed[:, 3]
    points_observed = np.dot(R, points_model) + T.reshape((3, 1))
    return points_observed 
Example 37
Source File: stereo_cameras.py    From StereoVision with GNU General Public License v3.0 5 votes vote down vote up
def get_point_cloud(self, pair):
        """Get 3D point cloud from image pair."""
        disparity = self.block_matcher.get_disparity(pair)
        points = self.block_matcher.get_3d(disparity,
                                           self.calibration.disp_to_depth_mat)
        colors = cv2.cvtColor(pair[0], cv2.COLOR_BGR2RGB)
        return PointCloud(points, colors) 
Example 38
Source File: visualization.py    From FCGF with MIT License 5 votes vote down vote up
def get_colored_point_cloud_feature(pcd, feature, voxel_size):
  tsne_results = embed_tsne(feature)

  color = get_color_map(tsne_results)
  pcd.colors = o3d.utility.Vector3dVector(color)
  spheres = mesh_sphere(pcd, voxel_size)

  return spheres 
Example 39
Source File: cloud_mask.py    From eo-learn with MIT License 5 votes vote down vote up
def get_s2_pixel_cloud_detector(threshold=0.4, average_over=4, dilation_size=2, all_bands=True):
    """ Wrapper function for pixel-based S2 cloud detector `S2PixelCloudDetector`
    """
    return S2PixelCloudDetector(threshold=threshold,
                                average_over=average_over,
                                dilation_size=dilation_size,
                                all_bands=all_bands)


# Twin classifier 
Example 40
Source File: AMSTaiwanSiteInformation.py    From pilot with Apache License 2.0 5 votes vote down vote up
def getCloudList(self):
        """ Return a list of all clouds """

        tier1 = self.setTier1Info()
        return tier1.keys() 
Example 41
Source File: project.py    From multilabel-image-classification-tensorflow with MIT License 5 votes vote down vote up
def get_cloud(depth, intrinsics_inv, name=None):
  """Convert depth map to 3D point cloud."""
  with tf.name_scope(name):
    dims = depth.shape.as_list()
    batch_size, img_height, img_width = dims[0], dims[1], dims[2]
    depth = tf.reshape(depth, [batch_size, 1, img_height * img_width])
    grid = _meshgrid_abs(img_height, img_width)
    grid = tf.tile(tf.expand_dims(grid, 0), [batch_size, 1, 1])
    cam_coords = _pixel2cam(depth, grid, intrinsics_inv)
    cam_coords = tf.transpose(cam_coords, [0, 2, 1])
    cam_coords = tf.reshape(cam_coords, [batch_size, img_height, img_width, 3])
    logging.info('depth -> cloud: %s', cam_coords)
    return cam_coords 
Example 42
Source File: point_cloud.py    From pylot with Apache License 2.0 5 votes vote down vote up
def get_closest_point_in_point_cloud(fwd_points, pixel, normalized=False):
        """Finds the closest point in the point cloud to the given point.

        Args:
            pixel (:py:class:`~pylot.utils.Vector2D`): Camera coordinates.

        Returns:
            :py:class:`~pylot.utils.Location`: Closest point cloud point.
        """
        # Select x and y.
        pc_xy = fwd_points[:, 0:2]
        # Create an array from the x, y coordinates of the point.
        xy = np.array([pixel.x, pixel.y]).transpose()

        # Compute distance
        if normalized:
            # Select z
            pc_z = fwd_points[:, 2]
            # Divize x, y by z
            normalized_pc = pc_xy / pc_z[:, None]
            dist = np.sum((normalized_pc - xy)**2, axis=1)
        else:
            dist = np.sum((pc_xy - xy)**2, axis=1)

        # Select index of the closest point.
        closest_index = np.argmin(dist)

        # Return the closest point.
        return Location(fwd_points[closest_index][0],
                        fwd_points[closest_index][1],
                        fwd_points[closest_index][2]) 
Example 43
Source File: cloud.py    From waterfall with Apache License 2.0 5 votes vote down vote up
def GetCloudStoragePath():
    if IsEmscriptenReleasesBot():
        return EMSCRIPTEN_RELEASES_CLOUD_STORAGE_PATH
    else:
        return WATERFALL_CLOUD_STORAGE_PATH 
Example 44
Source File: robot_console.py    From fluxclient with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_cloud_validation_code(self):
        code = self.robot_obj.get_cloud_validation_code()
        for key, value in code.items():
            logger.info("  %s=%s", key, value)
        logger.info("done") 
Example 45
Source File: segmentation.py    From director with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def getDisparityPointCloud(decimation=4, removeOutliers=True, removeSize=0, rangeThreshold=-1, imagesChannel='MULTISENSE_CAMERA', cameraName='CAMERA_LEFT'):

    p = cameraview.getStereoPointCloud(decimation, imagesChannel=imagesChannel, cameraName=cameraName, removeSize=removeSize, rangeThreshold=rangeThreshold)
    if not p:
      return None

    if removeOutliers:
        # attempt to scale outlier filtering, best tuned for decimation of 2 or 4
        scaling = (10*16)/(decimation*decimation)
        p = labelOutliers(p, searchRadius=0.06, neighborsInSearchRadius=scaling)
        p = thresholdPoints(p, 'is_outlier', [0.0, 0.0])

    return p 
Example 46
Source File: smartag_20180313.py    From alibabacloud-python-sdk-v2 with Apache License 2.0 5 votes vote down vote up
def get_cloud_connect_network_use_limit(
            self,
            resource_owner_id=None,
            resource_owner_account=None,
            region_id=None,
            owner_account=None,
            owner_id=None):
        api_request = APIRequest('GetCloudConnectNetworkUseLimit', 'GET', 'http', 'RPC', 'query')
        api_request._params = {
            "ResourceOwnerId": resource_owner_id,
            "ResourceOwnerAccount": resource_owner_account,
            "RegionId": region_id,
            "OwnerAccount": owner_account,
            "OwnerId": owner_id}
        return self._handle_request(api_request).result 
Example 47
Source File: obj_utils.py    From monopsr with MIT License 5 votes vote down vote up
def get_depth_map_point_cloud(sample_name, frame_calib, depth_dir):
    """Calculates the point cloud from a depth map

    Args:
        sample_name: sample name
        frame_calib: FrameCalib frame calibration
        depth_dir: folder with depth maps
        cam_idx: cam index (2 or 3)

    Returns:
        (3, N) point_cloud in the form [[x,...][y,...][z,...]]
    """
    depth_map_path = get_depth_map_path(sample_name, depth_dir)
    depth_map = depth_map_utils.read_depth_map(depth_map_path)
    depth_map_shape = depth_map.shape[0:2]

    # Calculate point cloud from depth map
    cam_p = frame_calib.p2
    # cam_p = frame_calib.p2 if cam_idx == 2 else frame_calib.p3

    # # TODO: Call depth_map_utils version
    return depth_map_utils.get_depth_point_cloud(depth_map, cam_p)

    # Calculate points from depth map
    depth_map_flattened = depth_map.flatten()
    xx, yy = np.meshgrid(np.arange(0, depth_map_shape[1], 1),
                         np.arange(0, depth_map_shape[0], 1))
    xx = xx.flatten() - cam_p[0, 2]
    yy = yy.flatten() - cam_p[1, 2]

    temp = np.divide(depth_map_flattened, cam_p[0, 0])
    x = np.multiply(xx, temp)
    y = np.multiply(yy, temp)
    z = depth_map_flattened

    # Get x offset (b_cam) from calibration: cam_mat[0, 3] = (-f_x * b_cam)
    x_offset = -cam_p[0, 3] / cam_p[0, 0]

    point_cloud = np.asarray([x + x_offset, y, z])

    return point_cloud.astype(np.float32) 
Example 48
Source File: preseed.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_curtin_cloud_config(request, node):
    """Compose the curtin cloud-config, which is only applied to
       Ubuntu core (by curtin)."""
    token = NodeKey.objects.get_token_for_node(node)
    datasource = {
        "datasource": {
            "MAAS": {
                "consumer_key": token.consumer.key,
                "token_key": token.key,
                "token_secret": token.secret,
                "metadata_url": request.build_absolute_uri(
                    reverse("metadata")
                ),
            }
        }
    }
    config = {
        "maas-datasource": {
            "path": "/etc/cloud/cloud.cfg.d/90_maas_datasource.cfg",
            "content": "datasource_list: [ MAAS ]",
        },
        "maas-cloud-config": {
            "path": "/etc/cloud/cloud.cfg.d/90_maas_cloud_config.cfg",
            "content": "#cloud-config\n%s" % yaml.safe_dump(datasource),
        },
    }
    # Add the Ubuntu SSO email if its set on the user.
    if node.owner is not None and node.owner.email:
        config["maas-ubuntu-sso"] = {
            "path": "/etc/cloud/cloud.cfg.d/90_maas_ubuntu_sso.cfg",
            "content": "#cloud-config\n%s"
            % yaml.safe_dump({"snappy": {"email": node.owner.email}}),
        }
    config["maas-reporting"] = {
        "path": "/etc/cloud/cloud.cfg.d/90_maas_cloud_init_reporting.cfg",
        "content": "#cloud-config\n%s"
        % yaml.safe_dump(get_cloud_init_reporting(request, node, token)),
    }
    return {"cloudconfig": config} 
Example 49
Source File: datagenerator.py    From 3DFeatNet with MIT License 5 votes vote down vote up
def get_point_cloud(self, i):
        """ Retrieves the i'th point cloud

        Args:
            i (int): Index of point cloud to retrieve

        Returns:
            cloud (np.array) point cloud containing N points, each of D dim
        """
        assert(0 <= i < len(self.data))

        cloud = DataGenerator.load_point_cloud(os.path.join(self.dataset_folder, self.paths_and_labels[i][0]),
                                               num_cols=self.num_cols)
        return cloud 
Example 50
Source File: compose_preseed.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_cloud_init_reporting(request, node, token):
    """Return the cloud-init metadata to enable reporting"""
    return {
        "reporting": {
            "maas": {
                "type": "webhook",
                "endpoint": request.build_absolute_uri(
                    reverse("metadata-status", args=[node.system_id])
                ),
                "consumer_key": token.consumer.key,
                "token_key": token.key,
                "token_secret": token.secret,
            }
        }
    } 
Example 51
Source File: list_instances.py    From python-cloud-utils with Apache License 2.0 5 votes vote down vote up
def get_cloud_from_zone(zone):
    for region in AWS_REGION_LIST:
        if region in zone:
            return 'aws'
    for region in GCP_REGION_LIST:
        if region in zone:
            return 'gcp'
    raise ValueError('Unknown zone %s' % zone) 
Example 52
Source File: delete_cf_dists.py    From jazz-installer with Apache License 2.0 5 votes vote down vote up
def getCloudFrontStatus(CFId):
    try:
        return cf_client.get_distribution(Id=CFId)
    except Exception:
        return False 
Example 53
Source File: cloud.py    From docassemble with MIT License 5 votes vote down vote up
def get_cloud():
    if S3_ENABLED:
        import docassemble.webapp.amazon
        cloud = docassemble.webapp.amazon.s3object(s3_config)
    elif AZURE_ENABLED:
        import docassemble.webapp.microsoft
        cloud = docassemble.webapp.microsoft.azureobject(azure_config)
    else:
        cloud = None
    return cloud 
Example 54
Source File: cloud.py    From docassemble with MIT License 5 votes vote down vote up
def get_custom_cloud(provider, config):
    if provider is None or config is None:
        return None
    if provider == 's3':
        import docassemble.webapp.amazon
        cloud = docassemble.webapp.amazon.s3object(config)
    elif provider == 'azure':
        import docassemble.webapp.microsoft
        cloud = docassemble.webapp.microsoft.azureobject(config)
    else:
        cloud = None
    return cloud 
Example 55
Source File: types.py    From kube-hunter with Apache License 2.0 5 votes vote down vote up
def get_cloud(self):
        config = get_config()
        try:
            logger.debug("Checking whether the cluster is deployed on azure's cloud")
            # Leverage 3rd tool https://github.com/blrchen/AzureSpeed for Azure cloud ip detection
            result = requests.get(
                f"https://api.azurespeed.com/api/region?ipOrUrl={self.host}", timeout=config.network_timeout,
            ).json()
            return result["cloud"] or "NoCloud"
        except requests.ConnectionError:
            logger.info("Failed to connect cloud type service", exc_info=True)
        except Exception:
            logger.warning(f"Unable to check cloud of {self.host}", exc_info=True)
        return "NoCloud" 
Example 56
Source File: obj_utils.py    From monopsr with MIT License 5 votes vote down vote up
def get_stereo_point_cloud(sample_name, calib_dir, disp_dir):
    """
    Gets the point cloud for an image calculated from the disparity map

    :param sample_name: sample name
    :param calib_dir: directory with calibration files
    :param disp_dir: directory with disparity images

    :return: (3, N) point_cloud in the form [[x,...][y,...][z,...]]
    """

    # Read calibration info
    frame_calib = calib_utils.get_frame_calib(calib_dir, sample_name)
    stereo_calibration_info = calib_utils.get_stereo_calibration(frame_calib.p2,
                                                                 frame_calib.p3)

    # Read disparity
    disp = cv2.imread(disp_dir + '/{}.png'.format(sample_name),
                      cv2.IMREAD_ANYDEPTH)
    disp = np.float32(disp)
    disp = np.divide(disp, 256)
    disp[disp == 0] = 0.1

    # Calculate the point cloud
    point_cloud = calib_utils.depth_from_disparity(disp, stereo_calibration_info)

    return point_cloud 
Example 57
Source File: robotviewbehaviors.py    From director with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def getObjectAsPointCloud(obj):
    try:
        obj = obj.model.polyDataObj
    except AttributeError:
        pass

    try:
        obj.polyData
    except AttributeError:
        return None

    if obj and obj.polyData.GetNumberOfPoints():# and (obj.polyData.GetNumberOfCells() == obj.polyData.GetNumberOfVerts()):
        return obj 
Example 58
Source File: coonswarp.py    From RasterFairy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def getCloudGrid( xyc,autoPerimeterOffset=True,autoPerimeterDensity=True,
                 width=64, height=64, perimeterSubdivisionSteps=4, paddingScale=1.05, 
                 smoothing=0.001, warpQuality=9, perimeterOffset=None ):
    bounds, densities = getCloudHull(xyc, width=width, height=height, perimeterSubdivisionSteps=perimeterSubdivisionSteps, 
                    smoothing=smoothing,autoPerimeterOffset=autoPerimeterOffset,
                    perimeterOffset=perimeterOffset,autoPerimeterDensity=autoPerimeterDensity)

    return getCoonsGrid(bounds, width=width, height=height,densities=densities,paddingScale=paddingScale)