This conversion helper is provided as a developer convenience while
transitioning from v1 to v2 of the API. On June 6, 2019, we will sunset
v1 of the API. At that time, this method will no longer function and we
will remove it from the SDK.

@deprecated
338144
public function convertLegacyToken(): void
    {
        $tokens = $this->requestAuthTokens(
            $this->auth->getPayload(),
            self::TRANSITION_URL
        );

        $this->accessToken = $tokens['accessToken'];
        $this->refreshToken = $tokens['refreshToken'];
        $this->ttl = $tokens['expiresIn'];
    }
247318
@Deprecated
    @Override
    @SuppressWarnings("deprecation")
    protected void rollbackRuntime(OperationContext context, ModelNode operation, ModelNode model, List<ServiceController<?>> controllers) {
        revertReload(context);
    }
434021
public ChannelBuffer formatVersionV1(final Map<String, String> version) {
    throw new BadRequestException(HttpResponseStatus.NOT_IMPLEMENTED, 
        "The requested API endpoint has not been implemented", 
        this.getClass().getCanonicalName() + 
        " has not implemented formatVersionV1");
  }
708586
def map_v2_event_into_v1(event):
    '''
    
    '''

    # return the event if it has already been mapped
    if "v2_event_mapped_into_v1" in event:
        return event

    # Trigger mapping code if enity exists and client does not
    if not bool(event.get('client')) and "entity" in event:
        event['client'] = event['entity']

        # Fill in missing client attributes
        if "name" not in event['client']:
            event['client']['name'] = event['entity']['id']

        if "subscribers" not in event['client']:
            event['client']['subscribers'] = event['entity']['subscriptions']

        # Fill in renamed check attributes expected in 1.4 event
        if "subscribers" not in event['check']:
            event['check']['subscribers'] = event['check']['subscriptions']

        if "source" not in event['check']:
            event['check']['source'] = event['check']['proxy_entity_id']

        # Mimic 1.4 event action based on 2.0 event state
        #  action used in logs and fluentd plugins handlers
        action_state_mapping = {'flapping': 'flapping', 'passing': 'resolve',
                                'failing': 'create'}

        if "state" in event['check']:
            state = event['check']['state']
        else:
            state = "unknown::2.0_event"

        if "action" not in event and state.lower() in action_state_mapping:
            event['action'] = action_state_mapping[state.lower()]
        else:
            event['action'] = state

        # Mimic 1.4 event history based on 2.0 event history
        if "history" in event['check']:
            # save the original history
            event['check']['history_v2'] = deepcopy(event['check']['history'])
            legacy_history = []
            for history in event['check']['history']:
                if isinstance(history['status'], int):
                    legacy_history.append(str(history['status']))
                else:
                    legacy_history.append("3")

            event['check']['history'] = legacy_history

        # Setting flag indicating this function has already been called
        event['v2_event_mapped_into_v1'] = True

    # return the updated event
    return event
1153860
@Override
    public final void visitConversionInstruction(ConversionInstruction obj) {
        visitConversionInstruction2(obj);
        if (obj instanceof NULL2Z) {
            visitNULL2Z((NULL2Z) obj);
        } else if (obj instanceof NONNULL2Z) {
            visitNONNULL2Z((NONNULL2Z) obj);
        }
    }
1291427
def convert(point)
      today = Date.new(year, month, day)
      new_seconds = seconds + fractional + (minutes + hours * 60) * 60

      # During daylight hours?
      if hours >= 6 && hours < 18
        start = NewTime.sunrise(today, point)
        finish = NewTime.sunset(today, point)
        new_start_hour = 6
      else
        # Is it before sunrise or after sunset?
        if hours < 6
          start = NewTime.sunset(today - 1, point)
          finish = NewTime.sunrise(today, point)
          new_start_hour = 18 - 24
        else
          start = NewTime.sunset(today, point)
          finish = NewTime.sunrise(today + 1, point)
          new_start_hour = 18
        end
      end
      start + (new_seconds.to_f / (60 * 60) - new_start_hour) * (finish - start) / 12
    end
1031259
function v4(options, buf, offset) {
    // Deprecated - 'format' argument, as supported in v1.2
    var i = buf && offset || 0;

    if (typeof(options) === 'string') {
      buf = (options === 'binary') ? new BufferClass(16) : null;
      options = null;
    }
    options = options || {};

    var rnds = options.random || (options.rng || _rng)();

    // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
    rnds[6] = (rnds[6] & 0x0f) | 0x40;
    rnds[8] = (rnds[8] & 0x3f) | 0x80;

    // Copy bytes to buffer, if provided
    if (buf) {
      for (var ii = 0; ii < 16; ii++) {
        buf[i + ii] = rnds[ii];
      }
    }

    return buf || unparse(rnds);
  }
1045191
ApiFuture<Void> begin() {
    BeginTransactionRequest.Builder beginTransaction = BeginTransactionRequest.newBuilder();
    beginTransaction.setDatabase(firestore.getDatabaseName());

    if (previousTransactionId != null) {
      beginTransaction
          .getOptionsBuilder()
          .getReadWriteBuilder()
          .setRetryTransaction(previousTransactionId);
    }

    ApiFuture<BeginTransactionResponse> transactionBeginFuture =
        firestore.sendRequest(
            beginTransaction.build(), firestore.getClient().beginTransactionCallable());

    return ApiFutures.transform(
        transactionBeginFuture,
        new ApiFunction<BeginTransactionResponse, Void>() {
          @Override
          public Void apply(BeginTransactionResponse beginTransactionResponse) {
            transactionId = beginTransactionResponse.getTransaction();
            pending = true;
            return null;
          }
        });
  }
1354714
private static function preReleaseGreaterThan(PreRelease $v1, PreRelease $v2)
    {
        // Pre-releases can be denoted as versionable (X.Y.Z) or greek (alpha.5)
        // We let versionable take precedence
        if (!self::versionableEquals($v1, $v2)) {
            // If v1 is bigger on the versionable level, it's bigger.
            return self::versionableGreaterThan($v1, $v2);
        }

        // "Greek" part is "bigger" for v1
        if ($v1->getGreek() !== $v2->getGreek()) {
            return self::greekLargerThan($v1->getGreek(), $v2->getGreek());
        }

        // Release number for v1 is bigger than v2's
        if ($v1->getReleaseNumber() > $v2->getReleaseNumber()) {
            return true;
        }

        return false;
    }
749607
public static void endStringConversion(Builder methodBuilder, TypeName typeMirror) {
		SQLTransform transform = SQLTransformer.lookup(typeMirror);

		switch (transform.getColumnType()) {
		case TEXT:
			return;
		case BLOB:
			methodBuilder.addCode(",$T.UTF_8)", StandardCharsets.class);
			break;
		case INTEGER:
		case REAL:
			methodBuilder.addCode(")");
			break;
		default:
			break;
		}
	}
1309180
function Translator(api, options) {
  var origLength = JSON.stringify(api, null, 2).length;
  var debugInfo = {flattened: {}, pruned: {}};
  var shapeName = 'S0';
  var shapeNameMap = {};
  var visitedShapes = {};

  function logResults() {
    console.log('** Generated', api.metadata.endpointPrefix + '-' +
      api.metadata.apiVersion +'.min.json' +
      (process.env.DEBUG ? ':' : ''));

    if (process.env.DEBUG) {
      var pruned = Object.keys(debugInfo.pruned);
      var flattened = Object.keys(debugInfo.flattened);
      var newLength = JSON.stringify(api, null, 2).length;
      console.log('- Pruned Shapes:', pruned.length);
      console.log('- Flattened Shapes:', flattened.length);
      console.log('- Remaining Shapes:', Object.keys(api.shapes).length);
      console.log('- Original Size:', origLength / 1024.0, 'kb');
      console.log('- Minified Size:', newLength / 1024.0, 'kb');
      console.log('- Size Saving:', (origLength - newLength) / 1024.0, 'kb');
      console.log('');
    }
  }

  function deleteTraits(obj) {
    if (!options.documentation) {
      delete obj.documentation;
      delete obj.documentationUrl;
      delete obj.errors;
      delete obj.min;
      delete obj.max;
      delete obj.pattern;
      delete obj['enum'];
      delete obj.box;
    }
  }

  function trackShapeDeclaration(ref) {
    if (ref.shape && !shapeNameMap[ref.shape]) {
      // found a shape declaration we have not yet visited.
      // assign a new generated name in the shapeNameMap & visit it
      var oldShapeName = ref.shape;
      ref.shape = shapeName = nextString(shapeName);

      visitedShapes[shapeName] = api.shapes[oldShapeName];
      shapeNameMap[oldShapeName] = {name: shapeName, refs: [ref]};

      traverseShapeRef(api.shapes[oldShapeName]);
    } else if (ref.shape && shapeNameMap[ref.shape]) {
      // we visited this shape before. keep track of this ref and rename
      // the referenced declaration to the generated name
      var map = shapeNameMap[ref.shape];
      map.refs.push(ref);
      ref.shape = map.name;        
    }
  }

  function pruneShapes() {
    // prune shapes visited only once or only have type specifiers
    each(shapeNameMap, function(name, map) {
      if (Object.keys(visitedShapes[map.name]).join() === 'type' &&
          ['structure','map','list'].indexOf(visitedShapes[map.name].type) < 0) {
        // flatten out the shape (only a scalar type property is on the shape)
        for (var i = 0; i < map.refs.length; i++) {
          var ref = map.refs[i];
          debugInfo.flattened[name] = true;
          delete ref.shape;
          ref.type = visitedShapes[map.name].type;

          // string type is default, don't need to specify this
          if (ref.type === 'string') delete ref.type;
        }

        // we flattened all refs, we can prune the shape too
        delete visitedShapes[map.name];
        debugInfo.pruned[name] = true;
      } else if (map.refs.length === 1) { // only visited once
        // merge shape data onto ref
        var shape = visitedShapes[map.name];

        for (var i = 0; i < map.refs.length; i++) {
          delete map.refs[i].shape;
          for (var prop in shape) {
            if (shape.hasOwnProperty(prop)) {
              //Translator prefers timestampFormat trait in members rather than in shape
              if (map.refs[i].hasOwnProperty(prop) && ['timestampFormat'].indexOf(prop) >= 0) {
                continue;
              }
              map.refs[i][prop] = shape[prop];
            }
            
          }
        }

        // delete the visited shape
        delete visitedShapes[map.name];
        debugInfo.pruned[name] = true;
      }
    });
  }

  function traverseShapeRef(ref) {
    if (!ref) return;

    deleteTraits(ref);

    traverseShapeRef(ref.key); // for maps
    traverseShapeRef(ref.value); // for maps
    traverseShapeRef(ref.member); // for lists

    // for structures
    each(ref.members || {}, function(key, value) { traverseShapeRef(value); });

    // resolve shape declarations
    trackShapeDeclaration(ref);
  }

  function traverseOperation(op) {
    deleteTraits(op);

    delete op.name;
    if (op.http) {
      if (op.http.method === 'POST') delete op.http.method;
      if (op.http.requestUri === '/') delete op.http.requestUri;
      if (Object.keys(op.http).length === 0) delete op.http;
    }

    traverseShapeRef(op.input);
    traverseShapeRef(op.output);    
  }

  function traverseApi() {
    deleteTraits(api);
    each(api.operations, function(name, op) { traverseOperation(op); });
    api.shapes = visitedShapes;
  }

  traverseApi();
  pruneShapes();
  logResults();
  return api;
}
446116
function initMetadataConversions() {
  var mdc = this.metadataConversions

  mdc['publish'] = {
    deserialize: function (dateString) {
      if (dateString)
        return new Date(Date.parse(dateString))
      else
        return dateString
    },
    serialize: function (date) {
      if (date instanceof Date) {
        return date.getFullYear() + '-' 
          + ('0' + (date.getMonth()+1)).slice(-2) + '-'
          + ('0' + date.getDate())
      } else {
        return date.toString()
      }
    }
  }

  mdc['tags'] = {
    deserialize: function (tagString) { //prob not very readable
      if (S(tagString).contains(',')) return tagString.split(',').map(function(tag){ return tag.trim() })
      //else if (S(tagString).contains(' ')) return tagString.split(' ').map(function(tag){ return tag.trim() })
      else return [tagString]
    },
    serialize: function (tagArray) {
      return tagArray.join(', ')
    }
  }
}
1095705
function replacePropagatingVersions(uri, data) {
  if (references.isPropagatingVersion(uri)) {
    references.replaceAllVersions(uri.split('@')[1])(data);
  }

  return data;
}
11933
@Deprecated
	public static String refund(Map<String, String> reqData) {
		return HttpUtils.post(SDKConfig.getConfig().getBackRequestUrl(), reqData);
	}
246729
@Deprecated
    public static ModelNode detypedFromChangeset(ModelNode prototype, Map<String, Object> changeSet, List<PropertyBinding> bindings)
    {
        // pre requesites
        prototype.require(ADDRESS);
        prototype.require(OP);

        ModelNode operation = new ModelNode();
        operation.get(OP).set(COMPOSITE);
        operation.get(ADDRESS).setEmptyList();

        List<ModelNode> steps = new ArrayList<ModelNode>();

        for(PropertyBinding binding : bindings)
        {

            Object value = changeSet.get(binding.getJavaName());
            if(value!=null)
            {
                ModelNode step = prototype.clone();
                step.get(NAME).set(binding.getDetypedName());

                Class type = value.getClass();
                if(FormItem.VALUE_SEMANTICS.class == type) {
                    // skip, it would be persisted as UNDEFINED otherwise
                }
                else if(String.class == type)
                {
                    step.get(VALUE).set((String) value);
                }
                else if(Boolean.class == type)
                {
                    step.get(VALUE).set((Boolean)value);
                }
                else if(Integer.class == type)
                {
                    step.get(VALUE).set((Integer)value);
                }
                else if(Double.class == type)
                {
                    step.get(VALUE).set((Double)value);
                }
                else
                {
                    throw new RuntimeException("Unsupported type: "+type);
                }

                steps.add(step);
            }
        }


        operation.get(STEPS).set(steps);
        return operation;
    }
1092536
@SuppressWarnings("unchecked")
    public void finish(final Convert convert, final Object obj) {
        finish(convert, (Type) null, obj);
    }
1259441
protected <T> T convertIfNecessary(String value, T originalValue) {
        if (originalValue == null) {
            return (T) value;
        }

        return TypeConversionUtils.convertIfNecessary(value, (Class<T>) originalValue.getClass());
    }