Update an API with a specification from a Swagger file
The update is done in the "overwrite" mode of API Gateway

@return {Promise} which resolves to the updated API
14033
function(apiId, swaggerPath) {
        return new Promise(function(resolve, reject) {
            fs.readFile(swaggerPath, function(err, data) {
                if (err) return reject(err);
                
                resolve(APIG.putRestApi({
                    restApiId: apiId,
                    body: data,
                    mode: 'overwrite'
                }).promise());
            });
        });
    }
1326811
def update_project(id, **kwargs):
    
    content = update_project_raw(id, **kwargs)
    if content:
        return utils.format_json(content)
940494
def file_needs_update?(filename: nil)
      # looking for something like: FastlaneRunnerAPIVersion [0.9.1]
      regex_to_use = API_VERSION_REGEX

      source = File.join(self.source_swift_code_file_folder_path, "/#{filename}")
      target = File.join(self.target_swift_code_file_folder_path, "/#{filename}")

      # target doesn't have the file yet, so ya, I'd say it needs to be updated
      return true unless File.exist?(target)

      source_file_content = File.read(source)
      target_file_content = File.read(target)

      bundled_version = source_file_content.match(regex_to_use)[1]
      target_version = target_file_content.match(regex_to_use)[1]
      file_versions_are_different = bundled_version != target_version

      UI.verbose("#{filename} FastlaneRunnerAPIVersion (bundled/target): #{bundled_version}/#{target_version}")
      files_are_different = source_file_content != target_file_content

      if files_are_different && !file_versions_are_different
        UI.verbose("File versions are the same, but the two files are not equal, so that's a problem, setting needs update to 'true'")
      end

      needs_update = file_versions_are_different || files_are_different

      return needs_update
    end
344734
function reFile(filename, nfilename) {
    return new Promise(function (fulfill, reject) {
        fs.rename(filename, nfilename, function (err) {
            return err ? reject(err) : fulfill();
        });
    });
}
525333
function update(user, callback) {
      var cb = callback || angular.noop;

      return User.update(user,
        function (user) {
          return cb(user);
        },
        function (err) {
          return cb(err);
        }).$promise;
    }
1082222
function(apiName, swaggerPath) {
        return new Promise(function(resolve, reject) {
            fs.readFile(swaggerPath, function(err, data) {
                if (err) return reject(err);
                
                resolve(APIG.importRestApi({
                    body: data,
                    failOnWarnings: false
                }).promise());
            });
        });
    }
965821
function()
    {
        if (this._executePromise)
            return this._executePromise;

        var q = this.clone();

        var table  = q._T.__name__;
        var page   = q._page;
        var fields = q._fields;

        // Create the query from our stuff
        var query = {};
        _(q._where.concat(q._like)).each(function (q) {
            query[q.key] = q.value;
        });

        var doneLoading      = Q.defer();
        this._executePromise = doneLoading.promise;

        var left = q._take;

        // A single iteration of fetching via the API. Called repeatedly in
        // the case of large / unbounded TAKES
        var loop = function() {

            // always take 1000 unless we're almost done
            var take = left < 1000 ? left : 1000;

            // Hit the API and incremement the page
            q._fetch(table, take, page++, query, fields).then(function(res) {

                // publish progress
                doneLoading.notify(q._results.length);

                if (left !== undefined) left -= res.length;

                // Either resolve the the promise with the results if we're
                // done or call the loop again

                if (q._doneLoading || left <= 0)
                    doneLoading.resolve(q._getResults());
                else
                    process.nextTick(loop);

            }).catch(function(err) {
                doneLoading.reject(err);
            });
        };

        // do tha damn thing
        loop();
        return doneLoading.promise;
    }
1374696
function(apiClient) {
    this.apiClient = apiClient || ApiClient.instance;



    /**
     * Finds a code
     * Finds a code
     * @param {String} codeId Id of the code
     * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/Code}
     */
    this.findCode = function(codeId) {
      var postBody = null;

      // verify the required parameter 'codeId' is set
      if (codeId == undefined || codeId == null) {
        throw "Missing the required parameter 'codeId' when calling findCode";
      }


      var pathParams = {
        'codeId': codeId
      };
      var queryParams = {
      };
      var headerParams = {
      };
      var formParams = {
      };

      var authNames = ['basicAuth'];
      var contentTypes = ['application/json;charset=utf-8'];
      var accepts = ['application/json;charset=utf-8'];
      var returnType = Code;

      return this.apiClient.callApi(
        '/codes/{codeId}', 'GET',
        pathParams, queryParams, headerParams, formParams, postBody,
        authNames, contentTypes, accepts, returnType
      );
    }


    /**
     * Lists codes
     * Lists codes
     * @param {Object} opts Optional parameters
     * @param {Array.<String>} opts.types Filter results by types
     * @param {String} opts.search Search codes by free-text query
     * @param {String} opts.sortBy define order (NATURAL or SCORE). Default is SCORE
     * @param {String} opts.sortDir ASC or DESC. Default is ASC
     * @param {Integer} opts.firstResult First result
     * @param {Integer} opts.maxResults Max results
     * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link Array.<module:model/Code>}
     */
    this.listCodes = function(opts) {
      opts = opts || {};
      var postBody = null;


      var pathParams = {
      };
      var queryParams = {
        'types': this.apiClient.buildCollectionParam(opts['types'], 'csv'),
        'search': opts['search'],
        'sortBy': opts['sortBy'],
        'sortDir': opts['sortDir'],
        'firstResult': opts['firstResult'],
        'maxResults': opts['maxResults']
      };
      var headerParams = {
      };
      var formParams = {
      };

      var authNames = ['basicAuth'];
      var contentTypes = ['application/json;charset=utf-8'];
      var accepts = ['application/json;charset=utf-8'];
      var returnType = [Code];

      return this.apiClient.callApi(
        '/codes', 'GET',
        pathParams, queryParams, headerParams, formParams, postBody,
        authNames, contentTypes, accepts, returnType
      );
    }
  }
1274558
function() {
    return new Promise((resolve, reject) => {
      let instance;
      if (this.modelElement.name === this.node.getName()) {
        instance = this.node;
      } else {
        instance = this.mapper.getObject(this.modelElement.path());
      }

      if (instance) {
        if (instance.isStarted()) {
          instance.__update__(timesUp('update(...)', 30000, (err) => {
            if (err) {
              this.log.error('Unable to update ' + instance.getPath());
              reject(err);
            } else {
              this.log.debug(instance.getPath());
              this.node.kCore.emitter.emit('instanceUpdated', instance);
              resolve();
            }
          }));
        }
      } else {
        reject(new Error(this.toString() + ' error: unable to update instance ' + this.modelElement.name));
      }
    });
  }
514844
function serveDereferencedSwaggerFile (req, res, next) {
    if (req.method === "GET" || req.method === "HEAD") {
      let configPath = getConfiguredPath(options.apiPath);
      configPath = util.normalizePath(configPath, router);
      let reqPath = util.normalizePath(req.path, router);

      if (reqPath === configPath) {
        if (context.api) {
          util.debug("%s %s => Sending the Swagger API as JSON", req.method, req.path);
          res.json(context.api);
        }
        else {
          util.warn("WARNING! The Swagger API is empty. Sending an HTTP 500 response to %s %s", req.method, req.path);
          res.status(500).json({});
        }
        return;
      }
    }

    next();
  }
484549
def update_api_endpoint():
    """"""
    environment = subprocess.check_output(['pipenv',
                                           'run',
                                           'runway',
                                           'whichenv']).decode().strip()
    environment_file = os.path.join(
        os.path.dirname(os.path.realpath(__file__)),
        'src',
        'environments',
        'environment.prod.ts' if environment == 'prod' else 'environment.ts'
    )
    cloudformation = boto3.resource('cloudformation')
    stack = cloudformation.Stack(STACK_PREFIX + environment)
    endpoint = [i['OutputValue'] for i in stack.outputs
                if i['OutputKey'] == 'ServiceEndpoint'][0]

    with open(environment_file, 'r') as stream:
        content = stream.read()
    content = re.sub(r'api_url: \'.*\'$',
                     "api_url: '%s/api'" % endpoint,
                     content,
                     flags=re.M)
    with open(environment_file, 'w') as stream:
        stream.write(content)
824734
function() {
        return new Promise(function(resolve, reject) {
            try{
                resolve(library.listSourceLanguagesLastModified());
            } catch (err) {
                reject(err);
            }
        }).then(function(languages) {
            return listResourceContainers()
                .then(function(results) {
                    // flatten modified_at
                    let local = {};
                    for(let info of results) {
                        try {
                            if(!local[info.language.slug]) local[info.language.slug] = -1;
                            let old = local[info.language.slug];
                            local[info.language.slug] = info.modified_at > old ? info.modified_at : old;
                        } catch (err) {
                            console.error(err);
                        }
                    }
                    return inferUpdates(local, languages);
                });
        });
    }
456347
function(router, target) {
    // By default, just patch the router's own methods.
    // If a target is given, then patch the router to call the target's methods
    target = target || router;

    // get(setting), which is different than get(path, fn)
    var get = router.get;

    // Wrap all of these methods to convert Swagger-style paths to Express-style paths
    var fns = {};
    ['use', 'route', 'all'].concat(swaggerMethods).forEach(function(method) {
      fns[method] = target[method];
      router[method] = function(path) {
        var args = _.drop(arguments, 0);

        // Special-case for `app.get(setting)`
        if (args.length === 1 && method === 'get') {
          return get.call(router, path);
        }

        // Convert Swagger-style path to Express-style path
        if (_.isString(path)) {
          args[0] = path.replace(util.swaggerParamRegExp, ':$1');
        }

        // Pass-through to the corresponding Express method
        var ret = fns[method].apply(target, args);

        if (router.__sortMiddleWare) {
          router.__sortMiddleWare();
        }

        return ret;
      };
    });
  }
759230
function updateSubmissionFile(req, res, next) {
  var fileUpdateOptions = req.appformsResultPayload.data;

  fileUpdateOptions.submission = {
    submissionId: req.params.id,
    fieldId: req.params.fieldId
  };

  //Remove the cached file when finished
  fileUpdateOptions.keepFile = false;

  //Adding A New File If Required
  fileUpdateOptions.addingNewSubmissionFile = req.addingNewSubmissionFile;

  //If not adding a new file, the fileId param is expected to be the file group id
  if (!fileUpdateOptions.addingNewSubmissionFile) {
    fileUpdateOptions.fileDetails.groupId = req.params.fileId;
  } else {
    fileUpdateOptions.fileDetails.hashName = req.params.fileId;
  }

  logger.debug("Middleware updateSubmissionFile ", {fileUpdateOptions: fileUpdateOptions});

  forms.updateSubmissionFile(_.extend(fileUpdateOptions, req.connectionOptions), submissionsHandler(constants.resultTypes.submissions, req, next));
}
1157822
function _prepareUpdates(explorer, updates) {
  // TODO: We're assigning the response object directly onto the model so we
  // don't have to loop through the (sometimes) massive response object.
  function customizer(objValue, srcValue, key) {
    if (_.isArray(objValue)) {
      return srcValue;
    } else if (key === 'time' && _.isPlainObject(objValue)) {
      return srcValue;
    }
  }
  var newModel = _.mergeWith({}, explorer, _.omit(updates, 'response'), customizer);
  if (updates.response) newModel.response = updates.response;

  // Check if the event collection has changed. Clear the property names if so.
  if (updates.query && updates.query.event_collection && updates.query.event_collection !== explorer.query.event_collection) {
    newModel.query.property_names = [];
  }

  if(newModel.query.analysis_type === 'funnel' && explorer.query.analysis_type !== 'funnel') {
    newModel = _migrateToFunnel(explorer, newModel);
  } else if(newModel.query.analysis_type !== 'funnel' && explorer.query.analysis_type === 'funnel') {
    newModel = _migrateFromFunnel(explorer, newModel);
  }
  newModel = _removeInvalidFields(newModel);

  return newModel;
}
731799
def _update(self, **kwargs):
        """"""
        path = self._construct_path_to_item()
        if not kwargs:
            return
        return self._http.put(path, json.dumps(kwargs))
1090121
function update(item, model, data, funcParams) {
    var working = [];
    var definedByData = [];

    _.forEach(data, function(value, key) {
        if (_.isFunction(value)) {
            working.push(Promise.resolve(value()).then(function(val) {
                item[key] = val;
            }));
        } else item[key] = value;
        definedByData.push(value);
    });

    _.forEach(model.itemDef, function(value, key) {
        if (value && value.__precalc) {
            var func = value.__precalc, previousVal = data[key];
            working.push(Promise.resolve(func.call(item, previousVal, funcParams || {})).then(function(val) {
                item[key] = (val && val._stWrapped) ? val.val : val;
            }));
        } // if the property has not been set from the itemDef yet. This allows item def properties to be changed
        else if (!_.has(item, key) || definedByData.indexOf(key) !== -1) item[key] = value;
    });

    return Promise.all(working);
}