language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
ClientStream returnStream() { synchronized (lock) { if (returnedStream == null) { // apply() has not been called, needs to buffer the requests. delayedStream = new DelayedStream(); return returnedStream = delayedStream; } else { return returnedStream; } } }
java
public String getTwoButtonsHtml( String label1, String label2, String onClick1, String onClick2, boolean firstActive) { StringBuffer result = new StringBuffer(); if (firstActive) { result.append( A_CmsHtmlIconButton.defaultButtonHtml( ...
java
public Observable<ServiceResponse<PatternAnyEntityExtractor>> getPatternAnyEntityInfoWithServiceResponseAsync(UUID appId, String versionId, UUID entityId) { if (this.client.endpoint() == null) { throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null."); ...
python
def refund(self, idempotency_key=None, **params): """Return a deferred.""" headers = populate_headers(idempotency_key) url = self.instance_url() + '/refund' d = self.request('post', url, params, headers) return d.addCallback(self.refresh_from).addCallback(lambda _: self)
python
def write_config_file(self, f, comments): """This method write a sample file, with attributes, descriptions, sample values, required flags, using the configuration object properties. """ if len(self.elements) < 1: return super(_Section, self).write_config_file...
python
def check_covariance_Kgrad_x(covar, relchange=1E-5, threshold=1E-2, check_diag=True): """ check_covariance_Kgrad_x(ACovarianceFunction covar, limix::mfloat_t relchange=1E-5, limix::mfloat_t threshold=1E-2, bool check_diag=True) -> bool Parameters ---------- covar: limix::ACovari...
python
def from_connection_string(cls, conn_str, eventhub=None, **kwargs): """Create an EventHubClient from a connection string. :param conn_str: The connection string. :type conn_str: str :param eventhub: The name of the EventHub, if the EntityName is not included in the connection s...
java
public void addTangoUserListener(ITangoUserListener listener, String attrName, boolean stateless) throws DevFailed { addTangoUserListener(listener, attrName, new String[0], stateless); }
java
protected void initField(Element elem, CmsXmlContentDefinition contentDef) throws CmsXmlException { String nameVal = elem.elementText(CmsConfigurationReader.N_PROPERTY_NAME); if (nameVal == null) { throw new CmsXmlException(Messages.get().container(Messages.ERR_XMLCONTENT_BAD_FIELD_NAME_1, ...
java
public void marshall(MaintenanceWindowAutomationParameters maintenanceWindowAutomationParameters, ProtocolMarshaller protocolMarshaller) { if (maintenanceWindowAutomationParameters == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { ...
java
private ConcurrentHashMap<String, BaseMethodBinding<?>> getMapForOperation(RestOperationTypeEnum operationType) { ConcurrentHashMap<String, BaseMethodBinding<?>> result = operationBindings.get(operationType); if(result == null) { operationBindings.putIfAbsent(operationType, new ConcurrentHashMap<String, BaseMeth...
python
def build_ricecooker_json_tree(args, options, metadata_provider, json_tree_path): """ Download all categories, subpages, modules, and resources from open.edu. """ LOGGER.info('Starting to build the ricecooker_json_tree') channeldir = args['channeldir'] if channeldir.endswith(os.path.sep): ...
python
def get_filesnames(self): """Return a list of all Taskwarrior projects as virtual files in the data directory""" self._update() projects = set(list(self._tasks.keys()) + self._task_projects + ['all_projects', 'unaffiliated']) return [join(self._data_location, p.split()[0]) for p in proje...
python
def MultiOpen(self, urns, mode="rw", token=None, aff4_type=None, age=NEWEST_TIME, follow_symlinks=True): """Opens a bunch of urns efficiently.""" if not data_store.AFF4Enabled(): raise NotImplementedError("AFF...
python
def params_to_dict(params, dct): """ Updates the 'dct' dictionary with the 'params' dictionary, filtering out all those whose param value is None. """ for param, val in params.items(): if val is None: continue dct[param] = val return dct
python
def __update_throughput(table_name, key_name, read_units, write_units): """ Update throughput on the DynamoDB table :type table_name: str :param table_name: Name of the DynamoDB table :type key_name: str :param key_name: Configuration option key name :type read_units: int :param read_units:...
python
def collect(self): """ Collect process stat data """ if not os.access(self.PROC, os.R_OK): return False # Open PROC file file = open(self.PROC, 'r') # Get data for line in file: if line.startswith('slabinfo'): cont...
python
def reverse_translate( protein_seq, template_dna=None, leading_seq=None, trailing_seq=None, forbidden_seqs=(), include_stop=True, manufacturer=None): """ Generate a well-behaved DNA sequence from the given protein sequence. If a template DNA sequence is specified, the returned DNA ...
python
def format_all(format_string, env): """ Format the input string using each possible combination of lists in the provided environment. Returns a list of formated strings. """ prepared_env = parse_pattern(format_string, env, lambda x, y: [FormatWrapper(x, z) for z in y]) # Generate each possible ...
python
def cut_sequences_relative(records, slices, record_id): """ Cuts records to slices, indexed by non-gap positions in record_id """ with _record_buffer(records) as r: try: record = next(i for i in r() if i.id == record_id) except StopIteration: raise ValueError("Rec...
java
@Override protected List<? extends Object> getFieldValues() { return Arrays.asList(hue(), saturation(), brightness(), opacity()); }
java
@Override public void discard(Object o) { BeanO beanO = (BeanO) o; beanO.destroy(); }
python
def handleUpgradeTxn(self, txn) -> None: """ Handles transaction of type POOL_UPGRADE Can schedule or cancel upgrade to a newer version at specified time :param txn: """ FINALIZING_EVENT_TYPES = [UpgradeLog.Events.succeeded, UpgradeLog.Events.failed] if ...
python
def basic_logging(self) -> None: """ Call this on the client object to create log handlers to output request and response messages. """ # Request handler if len(request_log.handlers) == 0: request_handler = logging.StreamHandler() request_handler.s...
java
protected void notFound(HttpServletRequest request, HttpServletResponse response) throws IOException { if(log.isDebugEnabled())log.debug("Not Found "+request.getRequestURI()); String method=request.getMethod(); // Not found special requests. if ...
python
def get_route_io_data_types(self): # type: () -> typing.List[UserDefined] """ Returns a list of all user-defined data types that are referenced as either an argument, result, or error of a route. If a List or Nullable data type is referenced, then the contained data type is retur...
java
@Function public static byte[] wrapMessage(GSSContext context, MessageProp prop, byte[] message) { try { // wrap the data and return the encrypted token byte[] initialToken = context.wrap(message, 0, message.length, prop); return getTokenWithLengthPrefix(initialToken); ...
java
protected void addRow(final KeyValue row) { long last_ts = 0; if (rows.size() != 0) { // Verify that we have the same metric id and tags. final byte[] key = row.key(); final iRowSeq last = rows.get(rows.size() - 1); final short metric_width = tsdb.metrics.width(); final short tags_...
java
public static String addNamedOutput(Job job, String namedOutput, OutputFormat outputFormat, Class<?> keyClass, Class<?> valueClass) throws FileNotFoundException, IOException, URISyntaxException { checkNamedOutputName(job, namedOutput, true); Configuration conf = job.getConfiguration(); String uniqueName...
java
@Override public void stop() throws LifecycleException { super.stop(); /* * Service should be stopped and removed otherwise in between start/stop/start of the container, * javax.management.InstanceAlreadyExistsException: mss-tomcat-embedded-6:type=SipApplicationDispatcher * exc...
python
def _readFile(self, fname, sldir): ''' private method that reads in and organizes the .DAT file Loads the data of the .DAT File into the variables cattrs and cols. In both these cases they are dictionaries, but in the case of cols, it is a dictionary of numpy array exect for the ...
java
public void deinit() { if (channel != null) try { channel.close(); } catch (IOException | TimeoutException e) { log.warn("Failed to close channel in RabbitMQ connector"); } if (connection != null) try { connection.close(); } catch (IOExceptio...
python
def _makna(self): """Mengembalikan representasi string untuk semua makna entri ini. :returns: String representasi makna-makna :rtype: str """ if len(self.makna) > 1: return '\n'.join( str(i) + ". " + str(makna) for i, makna in enumera...
java
@Nonnull public static <T> LConsumerBuilder<T> consumer(Consumer<LConsumer<T>> consumer) { return new LConsumerBuilder(consumer); }
java
private Method[] removeMessageEndpointMethods(Method[] listenerMethods) { ArrayList<Method> methods = new ArrayList<Method>(); for (Method method : listenerMethods) { String name = method.getName(); Class<?>[] params = method.getParameterTypes(); if ("afterDelivery"...
python
def do_execute_direct(self, code: str, silent: bool = False) -> [str, dict]: """ This is the main method that takes code from the Jupyter cell and submits it to the SAS server :param code: code from the cell :param silent: :return: str with either the log or list """ ...
python
def output_tree(self, t, seen): """Given a dependency tree of objects, output it in DFS order.""" if not t: return for c in t.children: self.output_tree(c, seen) if t.name in seen: return seen[t.name] = True if t.resource_name: ...
python
def stop(self, timeout=None): """Stop the thread.""" logger.debug("ports plugin - Close thread for scan list {}".format(self._stats)) self._stopper.set()
java
public Stream tumblingWindow(int windowCount, WindowsStoreFactory windowStoreFactory, Fields inputFields, Aggregator aggregator, Fields functionFields) { return window(TumblingCountWindow.of(windowCount), windowStoreFactory, inputFields, aggregator, functionFields); }
java
private static Bundle _loadBundle(BundleContext context, String path, InputStream is, boolean closeStream) throws BundleException { log(Log.LEVEL_INFO, "add bundle:" + path); try { // we make this very simply so an old loader that is calling this still works return context.installBundle(path, is); } fina...
java
public boolean eq(final Matrix B) { final Matrix A = this; if ((B.m_rows != A.m_rows) || (B.m_columns != A.m_columns)) { return false; } for (int i = 0; i < m_rows; i++) { for (int j = 0; j < m_columns; j++) { ...
python
def _send_command(self, cmd_class, command, payload, timeout=3.0): """ Send a BGAPI packet to the dongle and return the response """ if len(payload) > 60: return ValueError("Attempting to send a BGAPI packet with length > 60 is not allowed", actual_length=len(payload), comma...
java
public String[] get_object_property_list(Database database, String objname, String wildcard) throws DevFailed { if (!database.isAccess_checked()) checkAccess(database); String[] array = new String[2]; array[0] = objname; array[1] = wildcard; DeviceData argIn = new De...
java
public static <T> Filter<T> all(Collection<Filter<T>> filters) { return new MultiFilter<T>(filters) { @Override public T accept(T item) throws IOException { for (Filter<T> filter: filters) { filter.accept(item); } return...
java
public void setTransformFromLinesSquare( QrCode qr ) { // clear old points storagePairs2D.reset(); storagePairs3D.reset(); // use 3 of the corners to set the coordinate system // set(0, 0, qr.ppCorner,0); <-- prone to damage. Significantly degrades results if used set(0, 7, qr.ppCorner,1); set(7, 7, qr.pp...
python
def _evaluate_all_functions(self, xdata, p=None): """ This returns a list of function outputs given the stored data sets. This function relies on a previous call of set_data(). p=None means use the fit results """ if p is None: p = self.results[0] output = [] ...
python
def training_loop_hparams_from_scoped_overrides(scoped_overrides, trial_id): """Create HParams suitable for training loop from scoped HParams. Args: scoped_overrides: HParams, with keys all scoped by one of HP_SCOPES. These parameters are overrides for the base HParams created by create_loop_hparam...
java
@Override public boolean eIsSet(int featureID) { switch (featureID) { case TypesPackage.JVM_UNKNOWN_TYPE_REFERENCE__QUALIFIED_NAME: return QUALIFIED_NAME_EDEFAULT == null ? qualifiedName != null : !QUALIFIED_NAME_EDEFAULT.equals(qualifiedName); } return super.eIsSet(featureID); }
java
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { br_disable_responses result = (br_disable_responses) service.get_payload_formatter().string_to_resource(br_disable_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == S...
java
String getOption(String[] options, int index) { if ((options != null) && (options.length > index)) { return options[index]; } return null; }
java
@Override public void eSet(int featureID, Object newValue) { switch (featureID) { case BpsimPackage.CALENDAR__VALUE: setValue((String)newValue); return; case BpsimPackage.CALENDAR__ID: setId((String)newValue); return; case BpsimPackage.CALENDAR__NAME: setName((String)newValue); retur...
java
protected CmsResource getResource(CmsObject cms, I_CmsSearchDocument doc) { // check if the resource exits in the VFS, // this will implicitly check read permission and if the resource was deleted CmsResourceFilter filter = CmsResourceFilter.DEFAULT; if (isRequireViewPermission()) { ...
python
def toJulian(dt=None): """Converts a Python datetime to a Julian date, using the formula from Meesus (1991). This formula is reproduced in D.A. Vallado (2004). See: D.A. Vallado, Fundamentals of Astrodynamics and Applications, p. 187 http://books.google.com/books?id=PJLlWzMBKjkC&lpg=PA956...
java
protected synchronized void makeIndex() throws Exception { File indexFile = getIndexFile(filename); if (indexFile.exists()) try { loadIndex(indexFile); setIndexCreated(true); return; } catch (Exception x) { logger.warn(x.getMessage()); } ...
python
def v1_folder_list(request, kvlclient): '''Retrieves a list of folders for the current user. The route for this endpoint is: ``GET /dossier/v1/folder``. (Temporarily, the "current user" can be set via the ``annotator_id`` query parameter.) The payload returned is a list of folder identifiers. ...
java
public void signal() { if (lockVar.isHeldByCurrentThread()) { throw new RuntimeException("signal() must not be called on same thread as await()"); } try { lockVar.lock(); LOG.log(Level.INFO, "Signalling sleeper..."); isSignal = true; conditionVar.signal(); } finally { ...
python
def balance(self, account: Address): """ Return the balance of the account of the given address. """ return self.web3.eth.getBalance(to_checksum_address(account), 'pending')
python
def to_date(timeobject): """ Returns the ``datetime.datetime`` object corresponding to the time value conveyed by the specified object, which can be either a UNIXtime, a ``datetime.datetime`` object or an ISO8601-formatted string in the format `YYYY-MM-DD HH:MM:SS+00``. :param timeobject: the o...
python
def make_benchark(n_train, n_test, n_dim=2): """ Compute the benchmarks for Ordianry Kriging Parameters ---------- n_train : int number of points in the training set n_test : int number of points in the test set n_dim : int number of dimensions (default=2) Returns --...
python
def url(self): """The URL of the request (str).""" query = { 'key': self.api_key or default_api_key, 'person': self.person.to_json(), 'query_params_mode': self.query_params_mode, 'exact_name': self.exact_name, 'prioritize_records_by': ',...
java
public void displayTitle() throws Exception { JspWriter out = getJsp().getJspContext().getOut(); out.println(htmlStart()); out.println(bodyStart(null)); out.println(dialogStart()); out.println(dialogContentStart(getParamTitle())); out.println(dialogContentEnd()); ...
java
@Override public void setDescription(String description, java.util.Locale locale) { _cpSpecificationOption.setDescription(description, locale); }
python
def toggle_fold_trigger(self, block): """ Toggle a fold trigger block (expand or collapse it). :param block: The QTextBlock to expand/collapse """ if not TextBlockHelper.is_fold_trigger(block): return region = FoldScope(block) if region.collapsed: ...
python
def write_validate(ctx, param, value): """ Validate the -w option. Purpose: Validates the `-w`|`--write` option. Two arguments are expected. | The first is the mode, which must be in ['s', 'single', 'm', | 'multiple']. The mode determins if we're writing to one file for | all ...
java
public EntityNameAvailabilityCheckOutputInner checkNameAvailability(String locationName, CheckNameAvailabilityInput parameters) { return checkNameAvailabilityWithServiceResponseAsync(locationName, parameters).toBlocking().single().body(); }
python
def _new_object(self, objtype, name=None): r""" """ if objtype.startswith('net'): obj = openpnm.network.GenericNetwork(project=self, name=name) elif objtype.startswith('geo'): obj = openpnm.geometry.GenericGeometry(project=self, name=name) elif objtype.sta...
python
def pause(self, uuid): """ Pause a kvm domain by uuid :param uuid: uuid of the kvm container (same as the used in create) :return: """ args = { 'uuid': uuid, } self._domain_action_chk.check(args) self._client.sync('kvm.pause', args)
python
def identify_repo(repo_url): """Determine if `repo_url` should be treated as a URL to a git or hg repo. Repos can be identified by prepending "hg+" or "git+" to the repo URL. :param repo_url: Repo URL of unknown type. :returns: ('git', repo_url), ('hg', repo_url), or None. """ repo_url_values ...
java
@Override public Type getType() throws EFapsException { final Attribute attr = this.type.getAttribute(this.attrName); if (attr == null) { LinkToSelectPart.LOG.error("Could not find an Attribute with name '{}' for type:{}", this.attrName, this.type)...
java
private void updateDownloadStatus(S3Object result) { if (result == null) { download.setState(Transfer.TransferState.Canceled); download.setMonitor(new DownloadMonitor(download, null)); } else { download.setState(Transfer.TransferState.Completed); } }
java
public static Class<?> loadClass(String className) { try { return Class.forName(className); } catch(ClassNotFoundException e) { throw new IllegalArgumentException(e); } }
python
def plot_i1(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the second invariant I1 of the tensor: I1 = vxx*vyy + vyy*vzz + vxx*vzz - vxy**2 - vyz**2 - vxz**2 Usage ----- x.plot_i1([t...
java
public static void removeEntryFromSSLContextMap(String keyStorePath) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, "removeEntryFromSSLContextMap: " + new Object[] { keyStorePath }); List<SSLConfig> removeList = new ArrayList<SSLConfig>(); for (Entr...
python
def _draw_rectangle(data, obj, draw_options): """Return the PGFPlots code for rectangles. """ # Objects with labels are plot objects (from bar charts, etc). Even those without # labels explicitly set have a label of "_nolegend_". Everything else should be # skipped because they likely correspong t...
java
public Vector4d hermite(Vector4dc t0, Vector4dc v1, Vector4dc t1, double t, Vector4d dest) { double t2 = t * t; double t3 = t2 * t; dest.x = (x + x - v1.x() - v1.x() + t1.x() + t0.x()) * t3 + (3.0 * v1.x() - 3.0 * x - t0.x() - t0.x() - t1.x()) * t2 + x * t + x; dest.y = (y + y - v1.y() -...
java
@SuppressWarnings("unchecked") @Override public EList<String> getUKnotsAsString() { return (EList<String>) eGet(Ifc4Package.Literals.IFC_BSPLINE_SURFACE_WITH_KNOTS__UKNOTS_AS_STRING, true); }
python
def _full_keys(keys, ndim): """ Given keys such as those passed to ``__getitem__`` for an array of ndim, return a fully expanded tuple of keys. In all instances, the result of this operation should follow: array[keys] == array[_full_keys(keys, array.ndim)] """ if not isinstance(keys, ...
python
def fetch(cls, channel, start, end, bits=None, host=None, port=None, verbose=False, connection=None, type=Nds2ChannelType.any()): """Fetch data from NDS into a `StateVector`. Parameters ---------- channel : `str`, `~gwpy.detector.Channel` the name of the channe...
java
public static base_response add(nitro_service client, dnspolicylabel resource) throws Exception { dnspolicylabel addresource = new dnspolicylabel(); addresource.labelname = resource.labelname; addresource.transform = resource.transform; return addresource.add_resource(client); }
java
@Override public void propagate(int evtmask) throws ContradictionException { for (int i = 0; i < n; i++) { dMax[i] = deg[i].getUB(); } super.propagate(evtmask); }
python
def self_inventory(self): """ Inventory output will only contain the server name and the session ID when a key is provided. Provide the same format as with the full inventory instead for consistency. """ if self.api_key is None: return {} if self._sel...
java
private static Parameter[] getParameters(Constructor<?> constructor, Type target) { return buildParameters(target, constructor.getParameterTypes(), constructor.getGenericParameterTypes(), TypeHelper.toClass(target).getTypeParameters()); }
java
@Override public boolean passes(final String scope) { if (skipTestScope && SCOPE_TEST.equals(scope)) { return true; } if (skipProvidedScope && SCOPE_PROVIDED.equals(scope)) { return true; } if (skipSystemScope && SCOPE_SYSTEM.equals(scope)) { ...
python
def password( self, length=10, special_chars=True, digits=True, upper_case=True, lower_case=True): """ Generates a random password. @param length: Integer. Length of a password @param special_chars: Boolean. Whether ...
python
def unregister_node_path(self, node): """ Unregisters given Node path from the **file_system_events_manager**. :param node: Node. :type node: FileNode or DirectoryNode or ProjectNode :return: Method success. :rtype: bool """ path = node.file if hasattr(n...
java
@Override public void unlockSet(int requestNumber, SIMessageHandle[] msgHandles, boolean reply) // f199593, F219476.2 { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "unlockSet", new Object[] { requestNumber,...
python
def _finalize_requires(self): """ Set `metadata.python_requires` and fix environment markers in `install_requires` and `extras_require`. """ if getattr(self, 'python_requires', None): self.metadata.python_requires = self.python_requires if getattr(self, 'extr...
java
public JSON with(PrettyPrinter pp) { if (_prettyPrinter == pp) { return this; } return _with(_features, _streamFactory, _treeCodec, _reader, _writer, pp); }
python
def update_cache_for_course(self, courseid): """ Clean/update the cache of all the tasks for a given course (id) :param courseid: """ to_drop = [] for (cid, tid) in self._cache: if cid == courseid: to_drop.append(tid) for tid in to_drop...
python
def addLocalCacheService(self): "adds a CacheService to the instatiated HendrixService" _cache = self.getCacheService() _cache.setName('cache_proxy') _cache.setServiceParent(self.hendrix)
java
public static <T1, T2> BiConsumer<T1, T2> softenBiConsumer(final CheckedBiConsumer<T1, T2> fn) { return (t1, t2) -> { try { fn.accept(t1, t2); } catch (final Throwable e) { throw throwSoftenedException(e); } }; }
java
@SuppressWarnings("checkstyle:hiddenfield") public <T, U extends T> void register(final Class<T> type, final Set<EventHandler<U>> handlers) { this.handlers.put(type, new ExceptionHandlingEventHandler<>( new BroadCastEventHandler<>(handlers), this.errorHandler)); }
python
def actions( self ): """ Returns a list of actions that are associated with this shortcut edit. :return [<QAction>, ..] """ output = [] for i in range(self.uiActionTREE.topLevelItemCount()): output.append(self.uiActionTREE.topLevelItem(i).action()...
java
public static scala.collection.Iterable linkedListToScalaIterable(LinkedList<?> linkedList) { return JavaConverters.asScalaIterableConverter(linkedList).asScala(); }
java
public ReadOnlyStyledDocument<PS, SEG, S> build() { ensureNotYetCreated(); if (paragraphList.isEmpty()) { throw new IllegalStateException("Cannot build a ReadOnlyStyledDocument with an empty list of paragraphs!"); } alreadyCreated = true; return new ReadOnlyStyledDocu...
python
def network_from_array(self, array): """impo Defines a network from an array. Parameters ---------- array : array 3D numpy array. """ if len(array.shape) == 2: array = np.array(array, ndmin=3).transpose([1, 2, 0]) teneto.utils.chec...
java
public AttackDetail withAttackCounters(SummarizedCounter... attackCounters) { if (this.attackCounters == null) { setAttackCounters(new java.util.ArrayList<SummarizedCounter>(attackCounters.length)); } for (SummarizedCounter ele : attackCounters) { this.attackCounters.add(...
python
def pad_char(text: str, width: int, char: str = '\n') -> str: """Pads a text until length width.""" dis = width - len(text) if dis < 0: raise ValueError if dis > 0: text += char * dis return text
java
public static <T> T min(final T[] a, final Comparator<? super T> cmp) { N.checkArgNotNullOrEmpty(a, "The spcified array 'a' can not be null or empty"); return min(a, 0, a.length, cmp); }
python
def compute_uncertainty_reward(logits, predictions): """Uncertainty reward based on logits.""" # TODO(rsepassi): Add support for L1/L2 loss models. Current code only # works for softmax models. vocab_size = logits.shape[-1] assert vocab_size > 1 log_probs = common_layers.log_prob_from_logits(logits) max_l...