Updates the privacy of a dataset
966490
def _update_privacy(self, table_name, privacy):
        """"""
        ds_manager = DatasetManager(self.auth_client)
        dataset = ds_manager.get(table_name)
        dataset.privacy = privacy
        dataset.save()
1349622
def update(self, id):
        """"""
        # url('DataStores', id=ID)
        content = request.environ['wsgi.input'].read(int(request.environ['CONTENT_LENGTH']))
        content = content.decode('utf8')
        content = simplejson.loads(content)        
        result = meta.Session.query(DataStore).get(id)
        result.name = content['name']
        result.type = content['type']
        result.ogrstring = content['ogrstring']
        meta.Session.commit()
        response.status = 201
825174
def prepare_new_dataset():
    

    parser = argparse.ArgumentParser(
        description=(
            "Python client to Prepare a dataset"))
    parser.add_argument(
        "-u",
        help="username",
        required=False,
        dest="user")
    parser.add_argument(
        "-p",
        help="user password",
        required=False,
        dest="password")
    parser.add_argument(
        "-e",
        help="user email",
        required=False,
        dest="email")
    parser.add_argument(
        "-a",
        help="url endpoint with default http://localhost:8010",
        required=False,
        dest="url")
    parser.add_argument(
        "-f",
        help="file to use default ./examples/test-keras-dnn.json",
        required=False,
        dest="prepare_file")
    parser.add_argument(
        "-b",
        help=(
            "optional - path to CA bundle directory for "
            "client encryption over HTTP"),
        required=False,
        dest="ca_dir")
    parser.add_argument(
        "-c",
        help=(
            "optional - path to x509 certificate for "
            "client encryption over HTTP"),
        required=False,
        dest="cert_file")
    parser.add_argument(
        "-k",
        help=(
            "optional - path to x509 key file for "
            "client encryption over HTTP"),
        required=False,
        dest="key_file")
    parser.add_argument(
        "-s",
        help="silent",
        required=False,
        dest="silent",
        action="store_true")
    parser.add_argument(
        "-d",
        help="debug",
        required=False,
        dest="debug",
        action="store_true")
    args = parser.parse_args()

    user = ev(
        "API_USER",
        "user-not-set")
    password = ev(
        "API_PASSWORD",
        "password-not-set")
    email = ev(
        "API_EMAIL",
        "email-not-set")
    url = ev(
        "API_URL",
        "http://localhost:8010")
    prepare_file = ev(
        "DATAFILE",
        "prepare_file-not-set")
    ca_dir = os.getenv(
        "API_CA_BUNDLE_DIR",
        None)
    cert_file = os.getenv(
        "API_CERT_FILE",
        None)
    key_file = os.getenv(
        "API_KEY_FILE",
        None)
    verbose = bool(str(ev(
        "API_VERBOSE",
        "true")).lower() == "true")
    debug = bool(str(ev(
        "API_DEBUG",
        "false")).lower() == "true")

    if args.user:
        user = args.user
    if args.password:
        password = args.password
    if args.email:
        email = args.email
    if args.url:
        url = args.url
    if args.prepare_file:
        prepare_file = args.prepare_file
    if args.ca_dir:
        ca_dir = args.ca_dir
    if args.cert_file:
        cert_file = args.cert_file
    if args.key_file:
        key_file = args.key_file
    if args.silent:
        verbose = False
    if args.debug:
        debug = True

    usage = (
        "Please run with "
        "-u <username> "
        "-p <password> "
        "-a <AntiNex URL http://localhost:8010> "
        "-f <path to prepare file> "
        "-b <optional - path to CA bundle directory> "
        "-c <optional - path to x509 ssl certificate file> "
        "-k <optional - path to x509 ssl key file>")

    valid = True
    if not user or user == "user-not-set":
        log.error("missing user")
        valid = False
    if not password or password == "password-not-set":
        log.error("missing password")
        valid = False
    if not prepare_file or prepare_file == "prepare_file-not-set":
        log.error("missing prepare_file")
        valid = False
    else:
        if not os.path.exists(prepare_file):
            log.error(("did not find prepare_file={} on disk")
                      .format(
                        prepare_file))
            valid = False
    if not valid:
        log.error(usage)
        sys.exit(1)

    if verbose:
        log.info(("creating client user={} url={} file={}")
                 .format(
                    user,
                    url,
                    prepare_file))

    client = AIClient(
        user=user,
        email=email,
        password=password,
        url=url,
        ca_dir=ca_dir,
        cert_file=cert_file,
        key_file=key_file,
        verbose=verbose,
        debug=debug)

    if verbose:
        log.info(("loading request in prepare_file={}")
                 .format(
                    prepare_file))

    req_body = None
    with open(prepare_file, "r") as f:
        req_body = json.loads(f.read())

    if verbose:
        log.info("running prepare")

    prepare_was_started = False
    response = client.run_prepare(
        body=req_body)

    if response["status"] == SUCCESS:
        log.info(("prepare started with response={}")
                 .format(
                    response["data"]))
        prepare_was_started = True
    elif response["status"] == FAILED:
        log.error(("prepare failed with error='{}' with response={}")
                  .format(
                    response["error"],
                    response["data"]))
    elif response["status"] == ERROR:
        log.error(("prepare had an error='{}' with response={}")
                  .format(
                    response["error"],
                    response["data"]))
    elif response["status"] == LOGIN_FAILED:
        log.error(("prepare reported user was not able to log in "
                   "with an error='{}' with response={}")
                  .format(
                    response["error"],
                    response["data"]))

    if not prepare_was_started:
        sys.exit(1)

    if debug:
        log.info(("parsing response data={}")
                 .format(
                    response["data"]))
    else:
        if verbose:
            log.info("parsing data")

    prepare_data = response["data"]

    if not prepare_data:
        log.error(("missing prepare dictionary in response data={}")
                  .format(
                    response["data"]))
        sys.exit(1)

    prepare_id = prepare_data.get("id", None)
    prepare_status = prepare_data.get("status", None)

    log.info(("started prepare.id={} prepare.status={}")
             .format(
                prepare_id,
                prepare_status))

    prepare_results = client.wait_for_prepare_to_finish(
        prepare_id=prepare_id)

    if prepare_results["status"] != SUCCESS:
        log.error(("failed waiting for prepare.id={} to finish "
                   "error={} data={}")
                  .format(
                    prepare_id,
                    prepare_results["error"],
                    prepare_results["data"]))
        sys.exit(1)

    final_prepare = prepare_results["data"]

    log.info(("prepare={}")
             .format(
                ppj(final_prepare)))

    log.info(("prepare.id={} is done")
             .format(
                prepare_id))
49509
def update_dataset(dataset_id, name, data_type, val, unit_id, metadata={}, flush=True, **kwargs):
    

    if dataset_id is None:
        raise HydraError("Dataset must have an ID to be updated.")

    user_id = kwargs.get('user_id')

    dataset = db.DBSession.query(Dataset).filter(Dataset.id==dataset_id).one()
    #This dataset been seen before, so it may be attached
    #to other scenarios, which may be locked. If they are locked, we must
    #not change their data, so new data must be created for the unlocked scenarios
    locked_scenarios = []
    unlocked_scenarios = []
    for dataset_rs in dataset.resourcescenarios:
        if dataset_rs.scenario.locked == 'Y':
            locked_scenarios.append(dataset_rs)
        else:
            unlocked_scenarios.append(dataset_rs)

    #Are any of these scenarios locked?
    if len(locked_scenarios) > 0:
        #If so, create a new dataset and assign to all unlocked datasets.
        dataset = add_dataset(data_type,
                                val,
                                unit_id,
                                metadata=metadata,
                                name=name,
                                user_id=kwargs['user_id'])
        for unlocked_rs in unlocked_scenarios:
            unlocked_rs.dataset = dataset

    else:

        dataset.type  = data_type
        dataset.value = val
        dataset.set_metadata(metadata)

        dataset.unit_id = unit_id
        dataset.name  = name
        dataset.created_by = kwargs['user_id']
        dataset.hash  = dataset.set_hash()

        #Is there a dataset in the DB already which is identical to the updated dataset?
        existing_dataset = db.DBSession.query(Dataset).filter(Dataset.hash==dataset.hash, Dataset.id != dataset.id).first()
        if existing_dataset is not None and existing_dataset.check_user(user_id):
            log.warning("An identical dataset %s has been found to dataset %s."
                     " Deleting dataset and returning dataset %s",
                     existing_dataset.id, dataset.id, existing_dataset.id)
            db.DBSession.delete(dataset)
            dataset = existing_dataset
    if flush==True:
        db.DBSession.flush()

    return dataset
392135
def unlink(client, name, include, exclude, yes):
    """"""
    dataset = client.load_dataset(name=name)
    records = _filter(
        client, names=[dataset.name], include=include, exclude=exclude
    )

    if not yes and records:
        prompt_text = (
            'You are about to remove '
            'following from "{0}" dataset.\n'.format(dataset.name) +
            '\n'.join([str(record.full_path)
                       for record in records]) + '\nDo you wish to continue?'
        )
        click.confirm(WARNING + prompt_text, abort=True)

    if records:
        for item in records:
            dataset.unlink_file(item.path)

        dataset.to_yaml()
        click.secho('OK', fg='green')
349607
def update_name(self, force=False, create_term=False, report_unchanged=True):
        """"""

        updates = []

        self.ensure_identifier()

        name_term = self.find_first('Root.Name')

        if not name_term:
            if create_term:
                name_term = self['Root'].new_term('Root.Name','')
            else:
                updates.append("No Root.Name, can't update name")
                return updates

        orig_name = name_term.value

        identifier = self.get_value('Root.Identifier')

        datasetname = self.get_value('Root.Dataset')

        if datasetname:

            name = self._generate_identity_name()

            if name != orig_name or force:
                name_term.value = name
                updates.append("Changed Name")
            else:
                if report_unchanged:
                    updates.append("Name did not change")

        elif not orig_name:

            if not identifier:
                updates.append("Failed to find DatasetName term or Identity term. Giving up")

            else:
                updates.append("Setting the name to the identifier")
                name_term.value = identifier

        elif orig_name == identifier:
            if report_unchanged:
                updates.append("Name did not change")

        else:
            # There is no DatasetName, so we can't gneerate name, and the Root.Name is not empty, so we should
            # not set it to the identity.
            updates.append("No Root.Dataset, so can't update the name")

        return updates
956589
def delete_dataset(self, dataset):
        
        
        uri = URITemplate(self.baseuri + '/{owner}/{id}').expand(
            owner=self.username, id=dataset)
        return self.session.delete(uri)
314005
def marvcli_undiscard(datasets):
    """"""
    create_app()

    setids = parse_setids(datasets, discarded=True)
    dataset = Dataset.__table__
    stmt = dataset.update()\
                  .where(dataset.c.setid.in_(setids))\
                  .values(discarded=False)
    db.session.execute(stmt)
    db.session.commit()
1015246
def update_allowed(self):
        
        return self.update_action.allowed(self.column.table.request,
                                          self.datum,
                                          self)
1057288
def datasets_update(self, dataset_name, dataset_info):
    
    url = Api._ENDPOINT + (Api._DATASETS_PATH % dataset_name)
    return datalab.utils.Http.request(url, method='PUT', data=dataset_info,
                                      credentials=self._credentials)
645671
def updateType(self, dataset, dataset_access_type):
        
        if( dataset == "" ):
            dbsExceptionHandler("dbsException-invalid-input", "DBSDataset/updateType. dataset is required.")

        conn = self.dbi.connection()
        trans = conn.begin()

        try :
            self.updatetype.execute(conn, dataset, dataset_access_type.upper(), trans)
            trans.commit()
            trans = None
        except SQLAlchemyDatabaseError as ex:
            if str(ex).find("ORA-01407") != -1:
                dbsExceptionHandler("dbsException-invalid-input2", "Invalid Input", None, "DBSDataset/updateType. A Valid dataset_access_type is required.")
        finally:
            if trans:
                trans.rollback()
            if conn:
                conn.close()
928563
def delete(self, dataset):
        """"""

        url = self._get_url('/api/1.0/meta/dataset/{}/delete'.format(dataset))

        json_data = ''
        binary_data = json_data.encode()

        headers = self._get_request_headers()
        req = urllib.request.Request(url, binary_data, headers)
        resp = urllib.request.urlopen(req)   
        str_response = resp.read().decode('utf-8')
        if str_response != '"successful"' or resp.status < 200 or resp.status >= 300:
            msg = 'Dataset has not been deleted, because of the following error(s): {}'.format(str_response)
            raise ValueError(msg)
1097609
function(dataset){
    arrayRemove(this.sources, dataset);

    // remove event listeners from dataset
    if (this.listen.source)
      dataset.removeHandler(this.listen.source, this);

    // process removing dataset objects and update member map
    var memberMap = this.members_;
    for (var objectId in dataset.items_)
      memberMap[objectId].count--;
  }
1228408
def delete(dataset):
    """"""
    
    config = ApiConfig()
    client = ApiClient(config.host, config.app_id, config.app_secret)
    client.check_correct_host()
    client.delete(dataset)
    return ('Dataset {} has been deleted successfully'.format(dataset))
427040
def UpdateKnowledgeBase(self, response, provides):
    """"""

    if isinstance(response, rdf_anomaly.Anomaly):
      return

    if isinstance(response, rdf_client.User):
      self.knowledge_base.MergeOrAddUser(response)
      return

    if isinstance(response, rdf_protodict.Dict):
      response_dict = response.ToDict()
      for attribute, value in iteritems(response_dict):
        if attribute in provides:
          self.SetKnowledgeBaseValue(attribute, value)
      return

    # If its not a dict we only support a single value.
    if len(provides) == 1:
      self.SetKnowledgeBaseValue(provides[0], response)
818887
def filter_data(self):
        '''
        '''

        if not self.dataset_cases or not self.analysis_data:
            # colortext.error('No dataset cases or analysis (DDG) data were passed. Cannot filter the data. If you are using an existing dataframe, this may explain why no data was passed.')
            return
        if self.restrict_to or self.remove_cases:

            # Remove any cases with missing data
            available_cases = set(self.analysis_data.keys())
            missing_dataset_cases = [k for k in self.dataset_cases.keys() if k not in available_cases]
            for k in missing_dataset_cases:
                del self.dataset_cases[k]

            cases_to_remove = set()
            if self.restrict_to:
                # Remove cases which do not meet the restriction criteria
                if 'Exposed' in self.restrict_to:
                    for k, v in self.dataset_cases.iteritems():
                        for m in v['PDBMutations']:
                            if (m.get('ComplexExposure') or m.get('MonomericExposure')) <= self.burial_cutoff:
                                cases_to_remove.add(k)
                                break
            if self.remove_cases:
                # Remove cases which meet the removal criteria
                if 'Exposed' in self.remove_cases:
                    for k, v in self.dataset_cases.iteritems():
                        for m in v['PDBMutations']:
                            if (m.get('ComplexExposure') or m.get('MonomericExposure')) > self.burial_cutoff:
                                cases_to_remove.add(k)
                                break

            if cases_to_remove:
                colortext.warning('Filtering out {0} records.'.format(len(cases_to_remove)))

            for k in cases_to_remove:
                del self.dataset_cases[k]
                del self.analysis_data[k]
942618
def validate_data_privacy(request, data, wrapper_kw=None):
    
    from nefertari import wrappers
    if wrapper_kw is None:
        wrapper_kw = {}

    wrapper = wrappers.apply_privacy(request)
    allowed_fields = wrapper(result=data, **wrapper_kw).keys()
    data = data.copy()
    data.pop('_type', None)
    not_allowed_fields = set(data.keys()) - set(allowed_fields)

    if not_allowed_fields:
        raise wrappers.ValidationError(', '.join(not_allowed_fields))