language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def finalize(self): """finalize for PathConsumer""" super(TransposedConsumer, self).finalize() self.result = map(list, zip(*self.result))
java
public static Set<String> findAllDevices(AndroidDebugBridge adb, Integer minApiLevel) { Set<String> devices = new LinkedHashSet<>(); for (IDevice realDevice : adb.getDevices()) { if (minApiLevel == null) { devices.add(realDevice.getSerialNumber()); } else { DeviceDetails deviceDetail...
java
@Override public ClassDoc asClassDoc() { return env.getClassDoc((ClassSymbol)env.types.erasure(type).tsym); }
python
def update_source_list(self): """ update ubuntu 16 source list :return: """ with cd('/etc/apt'): sudo('mv sources.list sources.list.bak') put(StringIO(bigdata_conf.ubuntu_source_list_16), 'sources.list', use_sudo=True) sudo('ap...
python
def readBuffer(self, newLength): """ Read next chunk as another buffer. """ result = Buffer(self.buf, self.offset, newLength) self.skip(newLength) return result
python
def get_jokes(language='en', category='neutral'): """ Parameters ---------- category: str Choices: 'neutral', 'chuck', 'all', 'twister' lang: str Choices: 'en', 'de', 'es', 'gl', 'eu', 'it' Returns ------- jokes: list """ if language not in all_jokes: ra...
java
@Override public List<CommerceNotificationQueueEntry> findByCommerceNotificationTemplateId( long commerceNotificationTemplateId, int start, int end) { return findByCommerceNotificationTemplateId(commerceNotificationTemplateId, start, end, null); }
java
public static int readIntegerBigEndian(byte[] buffer, int offset) { int value; value = (buffer[offset] & 0xFF) << 24; value |= (buffer[offset + 1] & 0xFF) << 16; value |= (buffer[offset + 2] & 0xFF) << 8; value |= (buffer[offset + 3] & 0xFF); return value; }
java
public void setPropertyGroupDescriptions(java.util.Collection<PropertyGroup> propertyGroupDescriptions) { if (propertyGroupDescriptions == null) { this.propertyGroupDescriptions = null; return; } this.propertyGroupDescriptions = new java.util.ArrayList<PropertyGroup>(pro...
java
public HistoryReference getHistoryReference(int historyReferenceId) { DefaultHistoryReferencesTableEntry entry = getEntryWithHistoryId(historyReferenceId); if (entry != null) { return entry.getHistoryReference(); } return null; }
java
public final int getUint8(final int pos) { if (pos >= limit || pos < 0) throw new IllegalArgumentException("limit excceed: " + pos); return 0xff & buffer[origin + pos]; }
python
def _dirint_from_dni_ktprime(dni, kt_prime, solar_zenith, use_delta_kt_prime, temp_dew): """ Calculate DIRINT DNI from supplied DISC DNI and Kt'. Supports :py:func:`gti_dirint` """ times = dni.index delta_kt_prime = _delta_kt_prime_dirint(kt_prime, use_delta_kt_prim...
python
def walkerWrapper(callback): """ Wraps a callback function in a wrapper that will be applied to all [sub]sections. Returns: function """ def wrapper(*args,**kwargs): #args[0] => has to be the current walked section return Section.sectionWalker...
java
public static <T> Consumer<T> pipeline(Consumer<T> first, Consumer<T> second, Consumer<T> third) { return new PipelinedConsumer<T>(Iterations.iterable(first, second, third)); }
python
def _valid_deleted_file(path): ''' Filters file path against unwanted directories and decides whether file is marked as deleted. Returns: True if file is desired deleted file, else False. Args: path: A string - path to file ''' ret = False if path.endswith(' (deleted)'): ...
python
def Reinit(self, pid, auto_symfile_loading=True): """Reinitializes the object with a new pid. Since all modes might need access to this object at any time, this object needs to be long-lived. To make this clear in the API, this shorthand is supplied. Args: pid: the pid of the target process ...
python
def discover_upnp_devices( self, st="upnp:rootdevice", timeout=2, mx=1, retries=1 ): """ sends an SSDP discovery packet to the network and collects the devices that replies to it. A dictionary is returned using the devices unique usn as key """ # prepare UDP s...
python
def print_plugins(self): """Print the available plugins.""" width = console_width() line = Style.BRIGHT + '=' * width + '\n' middle = int(width / 2) if self.available_providers: print(line + ' ' * middle + 'PROVIDERS') for provider in sorted(self.available...
java
@SuppressWarnings("MissingPermission") static boolean getWifiConnected(Context context) { if (context != null && PackageManager.PERMISSION_GRANTED == context.checkCallingOrSelfPermission(Manifest.permission.ACCESS_NETWORK_STATE)) { ConnectivityManager connManager = (ConnectivityManager) context....
python
def _create_firefox_profile(self): """Create and configure a firefox profile :returns: firefox profile """ # Get Firefox profile profile_directory = self.config.get_optional('Firefox', 'profile') if profile_directory: self.logger.debug("Using firefox profile:...
java
public static String get(String bundleName, String key, Object[] args) { return get(bundleName, getLocale(), key, args); }
java
public void useProject(String projectName) { removeProject(projectName); recentProjectsList.addFirst(projectName); while (recentProjectsList.size() > MAX_RECENT_FILES) { recentProjectsList.removeLast(); } }
java
boolean handleStep(ListIterator<Step<?, ?>> stepIterator, MutableInt pathCount) { Step<?, ?> step = stepIterator.next(); removeTinkerPopLabels(step); if (step instanceof GraphStep) { doFirst(stepIterator, step, pathCount); } else if (this.sqlgStep == null) { boole...
python
def get_identifier(cmd_args, endpoint=''): """ Obtain anonmyzied identifier.""" student_email = get_student_email(cmd_args, endpoint) if not student_email: return "Unknown" return hashlib.md5(student_email.encode()).hexdigest()
python
def get(self, key, lang=None): """ Returns triple related to this node. Can filter on lang :param key: Predicate of the triple :param lang: Language of the triple if applicable :rtype: Literal or BNode or URIRef """ if lang is not None: for o in self.graph.ob...
python
def write_authorized_keys(user=None): """Write public keys back to authorized_keys file. Create keys directory if it doesn't already exist. args: user (User): Instance of User containing keys. returns: list: Authorised keys for the specified user. """ authorized_keys = list() a...
python
def evaluaterforces(Pot,R,z,phi=None,t=0.,v=None): """ NAME: evaluaterforces PURPOSE: convenience function to evaluate a possible sum of potentials INPUT: Pot - a potential or list of potentials R - cylindrical Galactocentric distance (can be Quantity) z - dista...
python
def get_host_advanced(name=None, ipv4addr=None, mac=None, **api_opts): ''' Get all host information CLI Example: .. code-block:: bash salt-call infoblox.get_host_advanced hostname.domain.ca ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host_advanced(name=name, mac=m...
java
private @CheckForNull HashedToken searchMatch(@Nonnull String plainSecret) { byte[] hashedBytes = plainSecretToHashBytes(plainSecret); for (HashedToken token : tokenList) { if (token.match(hashedBytes)) { return token; } } return null; ...
java
public static DataAttribute createDataAttribute(byte data[]) { DataAttribute attribute = new DataAttribute(); attribute.setData(data); return attribute; }
java
public void setLastPoint(double x, double y, double z) { if (this.numCoords>=3) { this.coords[this.numCoords-3] = x; this.coords[this.numCoords-2] = y; this.coords[this.numCoords-1] = z; this.graphicalBounds = null; this.logicalBounds = null; } }
python
def evaluate_unop(self, operation, right, **kwargs): """ Evaluate given unary operation with given operand. """ if not operation in self.unops: raise ValueError("Invalid unary operation '{}'".format(operation)) if right is None: return None return ...
python
def Convert(self, metadata, process, token=None): """Converts Process to ExportedProcess.""" result = ExportedProcess( metadata=metadata, pid=process.pid, ppid=process.ppid, name=process.name, exe=process.exe, cmdline=" ".join(process.cmdline), ctime=proc...
python
def _process_pathway_ko(self, limit): """ This adds the kegg orthologous group (gene) to the canonical pathway. :param limit: :return: """ LOG.info("Processing KEGG pathways to kegg ortholog classes") if self.test_mode: graph = self.testgraph ...
python
def reorderbydf(df2,df1): """ Reorder rows of a dataframe by other dataframe :param df2: input dataframe :param df1: template dataframe """ df3=pd.DataFrame() for idx,row in df1.iterrows(): df3=df3.append(df2.loc[idx,:]) return df3
java
@Override public ProjectFile read(InputStream stream) throws MPXJException { try { m_projectFile = new ProjectFile(); m_eventManager = m_projectFile.getEventManager(); m_calendarMap = new HashMap<Integer, ProjectCalendar>(); m_taskIdMap = new HashMap<Integer, Task>(); ...
java
public boolean returnReservedValues() throws FetchException, PersistException { synchronized (mStoredSequence) { if (mHasReservedValues) { Transaction txn = mRepository.enterTopTransaction(null); txn.setForUpdate(true); try { ...
java
public static CalendarMonth from(GregorianDate date) { PlainDate iso = PlainDate.from(date); // includes validation return CalendarMonth.of(iso.getYear(), iso.getMonth()); }
java
@InterfaceAudience.Private private void addValueEncryptionInfo(String path, String providerName, boolean escape) { if (escape) { path = path.replaceAll("~", "~0").replaceAll("/", "~1"); } if (this.encryptionPathInfo == null) { this.encryptionPathInfo = new HashMap<Str...
java
public boolean sendMessage(WebSocketMessage<?> message) { boolean sentSuccessfully = false; if (sessions.isEmpty()) { LOG.warn("No Web Socket session exists - message cannot be sent"); } for (WebSocketSession session : sessions.values()) { if (session != null && ...
java
public void marshall(KinesisDataStream kinesisDataStream, ProtocolMarshaller protocolMarshaller) { if (kinesisDataStream == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(kinesisDataStream.getArn(), ...
java
public void markAnnotation(String annotation, int lineno, int charno) { JSDocInfo.Marker marker = currentInfo.addMarker(); if (marker != null) { JSDocInfo.TrimmedStringPosition position = new JSDocInfo.TrimmedStringPosition(); position.setItem(annotation); position.setPositionInform...
python
async def self_check(cls): """ Check that the configuration is correct - Presence of "BERNARD_BASE_URL" in the global configuration - Presence of a "WEBVIEW_SECRET_KEY" """ async for check in super().self_check(): yield check s = cls.settings() ...
python
def add_extra_container(self, container, error_on_exists=False): """ Add a container as a 'extra'. These are running containers which are not necessary for running default CKAN but are useful for certain extensions :param container: The container name to add :param error_on_exist...
java
public boolean[] position(Range that){ boolean before = that.after(min); boolean after = that.before(max); boolean inside; if(before && after) inside = true; else if(!before && !after) inside = true; else if(before) inside = that.conta...
python
def edit(request, translation): """ Edit a translation. @param request: Django HttpRequest object. @param translation: Translation id @return Django HttpResponse object with the view or a redirection. """ translation = get_object_or_404(FieldTranslation, id=translation) if request.method == 'POST': if "cancel...
python
def do_move(self, dt, buttons): """ Updates velocity and returns Rects for start/finish positions """ assert isinstance(dt, int) or isinstance(dt, float) assert isinstance(buttons, dict) newVel = self.velocity # Redirect existing vel to new direction. nv...
python
def wigner_d(J, alpha, beta, gamma): u"""Return the Wigner D matrix for angular momentum J. We use the general formula from [Edmonds74]_, equation 4.1.12. The simplest possible example: >>> from sympy import Integer, symbols, pprint >>> half = 1/Integer(2) >>> alpha, beta, gamma = symbols("al...
java
@Override public void disableTable(TableName tableName) throws IOException { TableName.isLegalFullyQualifiedTableName(tableName.getName()); if (!tableExists(tableName)) { throw new TableNotFoundException(tableName); } if (isTableDisabled(tableName)) { throw new TableNotEnabledException(tab...
java
protected boolean isInside (int cross) { return (rule == WIND_NON_ZERO) ? Crossing.isInsideNonZero(cross) : Crossing.isInsideEvenOdd(cross); }
python
def put(url, data=None, **kwargs): """A wrapper for ``requests.put``. Sends a PUT request.""" _set_content_type(kwargs) if _content_type_is_json(kwargs) and data is not None: data = dumps(data) _log_request('PUT', url, kwargs, data) response = requests.put(url, data, **kwargs) _log_respo...
java
public java.util.List<FlowLog> getFlowLogs() { if (flowLogs == null) { flowLogs = new com.amazonaws.internal.SdkInternalList<FlowLog>(); } return flowLogs; }
python
def _setup_master(self): """ Construct a Router, Broker, and mitogen.unix listener """ self.broker = mitogen.master.Broker(install_watcher=False) self.router = mitogen.master.Router( broker=self.broker, max_message_size=4096 * 1048576, ) se...
python
def read_detections(fname): """ Read detections from a file to a list of Detection objects. :type fname: str :param fname: File to read from, must be a file written to by \ Detection.write. :returns: list of :class:`eqcorrscan.core.match_filter.Detection` :rtype: list .. note:: ...
java
@Override public void elemAdd(MVec addend) { if (addend instanceof Tensor) { elemAdd((Tensor)addend); } else { throw new IllegalArgumentException("Addend must be of type " + this.getClass()); } }
python
def as_percent(self, percent): """ Return a string representing a percentage of this progress bar. BarSet('1234567890', wrapper=('[, ']')).as_percent(50) >>> '[12345 ]' """ if not self: return self.wrap_str() length = len(self) # Using mod...
python
async def can_run(self, ctx): """|coro| Checks if the command can be executed by checking all the predicates inside the :attr:`.checks` attribute. Parameters ----------- ctx: :class:`.Context` The ctx of the command currently being invoked. Raises ...
java
public static File createOtherPlatformFile(File originalPlatform) { // calculate other platform sha1 for files larger than MAX_FILE_SIZE long length = originalPlatform.length(); if (length < MAX_FILE_SIZE && length < Runtime.getRuntime().freeMemory()) { try { byte[] b...
python
def grant_role(self, principal, role, obj=None): """Grant `role` to `user` (either globally, if `obj` is None, or on the specific `obj`).""" assert principal principal = unwrap(principal) session = object_session(obj) if obj is not None else db.session manager = self._cur...
python
def batched(iterable, size): """ Split an iterable into constant sized chunks Recipe from http://stackoverflow.com/a/8290514 """ length = len(iterable) for batch_start in range(0, length, size): yield iterable[batch_start:batch_start+size]
python
def write_code(self, name, code): """ Writes code to a python file called 'name', erasing the previous contents. Files are created in a directory specified by gen_dir_name (see function gen_file_path) File name is second argument of path """ file_path = self.gen_f...
java
private void reflect(int v, IBond bond) { visited[v] = true; IAtom atom = container.getAtom(v); atom.setPoint2d(reflect(atom.getPoint2d(), bond)); for (int w : graph[v]) { if (!visited[w]) reflect(w, bond); } }
java
public static <C> AsmClassAccess<C> get(Class<C> clazz) { @SuppressWarnings("unchecked") AsmClassAccess<C> access = (AsmClassAccess<C>) CLASS_ACCESSES.get(clazz); if (access != null) { return access; } Class<?> enclosingType = clazz.getEnclosingClass(); final bo...
python
def pyc2py(filename): """ Find corresponding .py name given a .pyc or .pyo """ if re.match(".*py[co]$", filename): if PYTHON3: return re.sub(r'(.*)__pycache__/(.+)\.cpython-%s.py[co]$' % PYVER, '\\1\\2.py', filename) else: ...
python
def required_unique(objects, key): """ A pyrsistent invariant which requires all objects in the given iterable to have a unique key. :param objects: The objects to check. :param key: A one-argument callable to compute the key of an object. :return: An invariant failure if any two or more objec...
python
def get_right_word(self, cursor=None): """ Gets the character on the right of the text cursor. :param cursor: QTextCursor where the search will start. :return: The word that is on the right of the text cursor. """ if cursor is None: cursor = self._editor.tex...
java
public boolean isDependentOn(String propertyName) { boolean dependent = false; if( getConstraint() instanceof PropertyConstraint ) { dependent = ((PropertyConstraint) getConstraint()).isDependentOn( propertyName ); } return super.isDependentOn( propertyName ) || dependent; ...
python
def pop(self): """ Removes the last node from the list """ popped = False result = None current_node = self._first_node while not popped: next_node = current_node.next() next_next_node = next_node.next() if not next_next_node: ...
python
def _get_resource_raw( self, cls, id, extra=None, headers=None, stream=False, **filters ): """Get an individual REST resource""" headers = headers or {} headers.update(self.session.headers) postfix = "/{}".format(extra) if extra else "" if cls.api_root != "a": ...
python
def column_spec_path(cls, project, location, dataset, table_spec, column_spec): """Return a fully-qualified column_spec string.""" return google.api_core.path_template.expand( "projects/{project}/locations/{location}/datasets/{dataset}/tableSpecs/{table_spec}/columnSpecs/{column_spec}", ...
java
@Override public void stop() { threadPoolExecutor.shutdown(); BlockingQueue<Runnable> taskQueue = threadPoolExecutor.getQueue(); int bufferSizeBeforeShutdown = threadPoolExecutor.getQueue().size(); boolean gracefulShutdown = true; try { gracefulShutdown = threadPoolExecutor.awaitTermination(...
java
@Override public CommerceAccountUserRel[] findByCommerceAccountId_PrevAndNext( CommerceAccountUserRelPK commerceAccountUserRelPK, long commerceAccountId, OrderByComparator<CommerceAccountUserRel> orderByComparator) throws NoSuchAccountUserRelException { CommerceAccountUserRel commerceAccountUserRel = findByP...
python
def current_length(self): # type: () -> int ''' Calculate the current length of this symlink record. Parameters: None. Returns: Length of this symlink record. ''' if not self._initialized: raise pycdlibexception.PyCdlibInternalError(...
java
private <T> T getTyped(PropertyKey key, Class<T> clazz) { Property p = getProperty(key.m_key); if (null == p || null == p.getData()) { return clazz.cast(m_defaults.get(key)); } return clazz.cast(p.getData()); }
java
@NonNull public static PaymentIntentParams createConfirmPaymentIntentWithSourceDataParams( @Nullable SourceParams sourceParams, @NonNull String clientSecret, @NonNull String returnUrl, boolean savePaymentMethod) { return new PaymentIntentParams() ...
java
public void setSharedAwsAccountIds(java.util.Collection<String> sharedAwsAccountIds) { if (sharedAwsAccountIds == null) { this.sharedAwsAccountIds = null; return; } this.sharedAwsAccountIds = new java.util.ArrayList<String>(sharedAwsAccountIds); }
python
def process_runway_configs(runway_dir=''): """Read the _application.json_ files. Args: runway_dir (str): Name of runway directory with app.json files. Returns: collections.defaultdict: Configurations stored for each environment found. """ LOG.info('Processing application.js...
python
def parse_subdomain_record(domain_name, rec, block_height, parent_zonefile_hash, parent_zonefile_index, zonefile_offset, txid, domain_zonefiles_missing, resolver=None): """ Parse a subdomain record, and verify its signature. @domain_name: the stem name @rec: the parsed zone file, with 't...
java
protected void startOutgoingConnection (final Connection conn, InetSocketAddress addr) { final SocketChannel sockchan = conn.getChannel(); try { // register our channel with the selector (if this fails, we abandon ship immediately) conn.selkey = sockchan.register(_selector, S...
python
def plot_weights(self, index=None, plot_type="motif_raw", figsize=None, ncol=1, **kwargs): """Plot filters as heatmap or motifs index = can be a particular index or a list of indicies **kwargs - additional arguments to concise.utils.plot.heatmap """ if "heatmap" in self.AVAILAB...
java
private Node getParent(Node n) { if (n.y_s == null) { return null; } Node c = n.y_s; if (c.o_c == n) { return c; } Node p1 = c.y_s; if (p1 != null && p1.o_c == n) { return p1; } return c; }
python
def get_password(config): """Returns the password for a remote server It tries to fetch the password from the following locations in this order: 1. config file [remote] section, password option 2. GNOME keyring 3. interactively, from the user """ password = config.get_option('remote...
java
public void marshall(ProvisioningArtifactParameter provisioningArtifactParameter, ProtocolMarshaller protocolMarshaller) { if (provisioningArtifactParameter == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.m...
java
public static WarInfo getWarInfo(File war) throws Exception { WarInfo info = new WarInfo(); info.setWarName(war.getName()); CadmiumWar warHelper = null; try { if(war != null && war.exists()) { warHelper = new FileBasedCadmiumWar(war); } else { warHelper = new ClasspathCadmium...
java
protected boolean isIntegerType(byte type) { return type == Const.T_INT || type == Const.T_BYTE || type == Const.T_BOOLEAN || type == Const.T_CHAR || type == Const.T_SHORT; }
java
public void mergeVertexDescription(VertexDescription src) { _touch(); if (src == m_description) return; // check if we need to do anything (if the src has same attributes) VertexDescription newdescription = VertexDescriptionDesignerImpl.getMergedVertexDescription(m_description, src); if (newdescription ==...
python
def log(*texts, sep = ""): """Log a text.""" text = sep.join(texts) count = text.count("\n") just_log("\n" * count, *get_time(), text.replace("\n", ""), sep=sep)
java
public void addCACertificatesToTrustStore(BufferedInputStream bis) throws CryptoException, InvalidArgumentException { if (bis == null) { throw new InvalidArgumentException("The certificate stream bis cannot be null"); } try { final Collection<? extends Certificate> cert...
java
public static SQLiteDatabase openOrCreateDatabase(File file, CursorFactory factory) { return openOrCreateDatabase(file.getPath(), factory); }
java
@Deprecated public final T parse(CharSequence source, String moduleName) { return new ScannerState(moduleName, source, 0, new SourceLocator(source)) .run(followedBy(Parsers.EOF)); }
java
public static void callStringBuilderLength(CodeBuilder b) { // Because of JDK1.5 bug which exposes AbstractStringBuilder class, // cannot use reflection to get method signature. TypeDesc stringBuilder = TypeDesc.forClass(StringBuilder.class); b.invokeVirtual(stringBuilder, "length", ...
java
public static boolean startsWithPattern( final byte[] byteArray, final byte[] pattern) { Preconditions.checkNotNull(byteArray); Preconditions.checkNotNull(pattern); if (pattern.length > byteArray.length) { return false; } for (int i = 0; i < pattern.length; ++i) { if (byteAr...
java
public final void reset() { for (int i = 0; i < combinationIndices.length; i++) { combinationIndices[i] = i; } remainingCombinations = totalCombinations; }
python
def get_seaborn_colorbar(dfr, classes): """Return a colorbar representing classes, for a Seaborn plot. The aim is to get a pd.Series for the passed dataframe columns, in the form: 0 colour for class in col 0 1 colour for class in col 1 ... colour for class in col ... n colour for ...
java
public void marshall(SourceAlgorithmSpecification sourceAlgorithmSpecification, ProtocolMarshaller protocolMarshaller) { if (sourceAlgorithmSpecification == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.mars...
java
public static RedwoodConfiguration parse(Properties props){ Set<String> used = new HashSet<String>(); //--Construct Pipeline //(handlers) Redwood.ConsoleHandler console = get(props,"log.toStderr","false",used).equalsIgnoreCase("true") ? Redwood.ConsoleHandler.err() : Redwood.ConsoleHandler.out(); ...
java
public void init(Range annotation, PropertyMetadata propertyMetadata) { m_maxExclusive = getValue(annotation.maxExclusive()); m_minExclusive = getValue(annotation.minExclusive()); m_maxInclusive = getValue(annotation.maxInclusive()); m_minInclusive = getValue(annotation.minInclusive(...
python
def standings(self, league_table, league): """Store output of league standings to a JSON file""" data = [] for team in league_table['standings'][0]['table']: item = {'position': team['position'], 'teamName': team['team'], 'playedGames': team['p...
python
def _get_parameters_from_request(self, request, exception=False): """Get parameters to log in OPERATION_LOG.""" user = request.user referer_url = None try: referer_dic = urlparse.urlsplit( urlparse.unquote(request.META.get('HTTP_REFERER'))) referer...
python
def prepare_handler(cfg): """ Load all files into single object. """ positions, velocities, box = None, None, None _path = cfg.get('_path', './') forcefield = cfg.pop('forcefield', None) topology_args = sanitize_args_for_file(cfg.pop('topology'), _path) if 'checkpoint' in cfg: r...