language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def add_var(self, var): """ Adds a variable to the model. """ if var.name in [v.name for v in self.vars]: logger.error("Variable set named '%s' already exists." % var.name) return var.i1 = self.var_N var.iN = self.var_N + var.N - 1 self.vars.appen...
python
def _operate(self, other, operation, inplace=True): """ Gives the CanonicalDistribution operation (product or divide) with the other factor. The product of two canonical factors over the same scope X is simply: C(K1, h1, g1) * C(K2, h2, g2) = C(K1+K2, h1+h2, g1+g2) ...
python
def update_counts(self, current): """ updates counts for the class instance based on the current dictionary counts args: ----- current: current dictionary counts """ for item in current: try: self.counts[item] += 1 ...
java
public void fillContent(CmsImageInfoBean imageInfo, CmsJSONMap imageAttributes, boolean initialFill) { for (Entry<Attribute, I_CmsFormWidget> entry : m_fields.entrySet()) { String val = imageAttributes.getString(entry.getKey().name()); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(val)) ...
java
private static void validate(RepresentationModel<?> resource, HalFormsAffordanceModel model) { String affordanceUri = model.getURI(); String selfLinkUri = resource.getRequiredLink(IanaLinkRelations.SELF.value()).expand().getHref(); if (!affordanceUri.equals(selfLinkUri)) { throw new IllegalStateException("Af...
python
def create_response(self, request, image, content_type): """Returns a response object for the given image. Can be overridden to return different responses.""" return HttpResponse(content=image, content_type=content_type)
java
@Override public final E fromString(final Map<String, Object> pAddParam, final String pStrVal) throws Exception { if (pStrVal == null || "".equals(pStrVal)) { return null; } return Enum.valueOf(this.enumClass, pStrVal); }
python
def fill_constants_types(module_name, elements): """ Recursively save arguments name and default value. """ for elem, intrinsic in elements.items(): if isinstance(intrinsic, dict): # Submodule case fill_constants_types(module_name + (elem,), intrinsic) elif isinstance(intrinsic, Con...
python
def aggregate(name): """ Perform an aggregation request. """ cube = get_cube(name) result = cube.aggregate(aggregates=request.args.get('aggregates'), drilldowns=request.args.get('drilldown'), cuts=request.args.get('cut'), or...
python
def get_image_info_by_image_name(self, image, exact_tag=True): """ using `docker images`, provide information about an image :param image: ImageName, name of image :param exact_tag: bool, if false then return info for all images of the given name regardless wha...
java
public void addClientObserver (ClientObserver observer) { _clobservers.add(observer); if (observer instanceof DetailedClientObserver) { _dclobservers.add((DetailedClientObserver)observer); } }
java
public static ClusterException create(Type type, String message) { switch (type) { case METASTORE: return new MetaStoreException(message); default: throw new IllegalArgumentException("Invalid exception type"); } }
python
def _combine_lines(self, lines): """ Combines a list of JSON objects into one JSON object. """ lines = filter(None, map(lambda x: x.strip(), lines)) return '[' + ','.join(lines) + ']'
python
def get_email_context(self,**kwargs): ''' This method can be overridden in classes that inherit from this mixin so that additional object-specific context is provided to the email template. This should return a dictionary. By default, only general financial context variabl...
java
public static <T, V> String interpose(T[] values, Iterator<V> separators) { return new InterposeStrings<T, V>().apply(new ArrayIterator<>(values), separators); }
python
def build_fncall( ctx, fndoc, argdocs=(), kwargdocs=(), hug_sole_arg=False, trailing_comment=None, ): """Builds a doc that looks like a function call, from docs that represent the function, arguments and keyword arguments. If ``hug_sole_arg`` is True, and the represented fun...
java
public static String toTimePrecision(final TimeUnit t) { switch (t) { case HOURS: return "h"; case MINUTES: return "m"; case SECONDS: return "s"; case MILLISECONDS: return "ms"; case MICRO...
java
public final void rulePredicatedRuleCall() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalXtext.g:883:2: ( ( ( rule__PredicatedRuleCall__Group__0 ) ) ) // InternalXtext.g:884:2: ( ( rule__PredicatedRuleCall__Group__0 ) ) {...
java
private Map<I_CmsResourceType, I_CmsPreviewProvider> getPreviewProviderForTypes(List<I_CmsResourceType> types) { Map<String, I_CmsPreviewProvider> previewProviderMap = new HashMap<String, I_CmsPreviewProvider>(); Map<I_CmsResourceType, I_CmsPreviewProvider> typeProviderMapping = new HashMap<I_CmsResour...
java
public static TStatus toTStatus(Exception e) { if (e instanceof HiveSQLException) { return ((HiveSQLException)e).toTStatus(); } TStatus tStatus = new TStatus(TStatusCode.ERROR_STATUS); tStatus.setErrorMessage(e.getMessage()); tStatus.setInfoMessages(toString(e)); return tStatus; }
python
def master_key_from_seed(seed): """ Generates a master key from a provided seed. Args: seed (bytes or str): a string of bytes or a hex string Returns: HDPrivateKey: the master private key. """ S = get_bytes(seed) I = hmac.new(b"Bitcoin seed", S, ...
java
void markKnownViewsInvalid() { final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final ViewHolder holder = getChildViewHolderInt(getChildAt(i)); if (holder != null) { holder.addFlags(ViewHolder.FLAG_UPDATE | ViewHolder.FLAG_INVALID); ...
java
public static <A extends Number & Comparable<?>> NumberExpression<Integer> sign(Expression<A> num) { return Expressions.numberOperation(Integer.class, Ops.MathOps.SIGN, num); }
java
public Response fetchHistoryAsOf(@PathParam("id") URI_ID id, @PathParam("asof") final Timestamp asOf) throws Exception { final MODEL_ID mId = tryConvertId(id); matchedFetchHistoryAsOf(mId, asOf); final Query<MODEL> query = server.find(modelType); def...
java
private String getConstantPoolString(final int cpIdx, final int subFieldIdx) throws ClassfileFormatException, IOException { final int constantPoolStringOffset = getConstantPoolStringOffset(cpIdx, subFieldIdx); return constantPoolStringOffset == 0 ? null : intern(inputStreamOr...
python
def _process_model_dict(self, d): """ Remove redundant items from a model's configuration dict. Parameters ---------- d : dict Modified in place. Returns ------- dict Modified `d`. """ del d['model_type'] ...
python
def installed(package, version): """ Check if the package meets the required version. The version specifier consists of an optional comparator (one of =, ==, >, <, >=, <=) and an arbitrarily long version number separated by dots. The should be as you would expect, e.g. for an installed version '0.1...
java
private static void includeAffected(Set<String> allClasses, Set<String> affectedClasses, List<File> sortedFiles) { Storer storer = Config.createStorer(); Hasher hasher = Config.createHasher(); NameBasedCheck classCheck = Config.DEBUG_MODE_V != Config.DebugMode.NONE ? new DebugNameCh...
python
def get_all_clusters(resource_root, view=None): """ Get all clusters @param resource_root: The root Resource object. @return: A list of ApiCluster objects. """ return call(resource_root.get, CLUSTERS_PATH, ApiCluster, True, params=view and dict(view=view) or None)
java
public static AbstractFile getFileByAbsolutePath(final SecurityContext securityContext, final String absolutePath) { try { return StructrApp.getInstance(securityContext).nodeQuery(AbstractFile.class).and(StructrApp.key(AbstractFile.class, "path"), absolutePath).getFirst(); } catch (FrameworkException ex) { ...
python
def wrap_existing_process(self, pid, stdout_read_fd, stderr_read_fd, port=None): """Do syncing, etc. for an already-running process. This returns after the process has ended and syncing is done. Captures ctrl-c's, signals, etc. """ stdout_read_file = os.fdopen(stdout_read_fd, 'r...
python
def clear(self): """ removes all documents in this collection """ collection = self.ds.connection(COLLECTION_MANAGED_PROCESS) return collection.delete_many(filter={})
python
def delete_chat_photo( self, chat_id: Union[int, str] ) -> bool: """Use this method to delete a chat photo. Photos can't be changed for private chats. You must be an administrator in the chat for this to work and must have the appropriate admin rights. Note: ...
java
@Action(name = "Modify Instance Attribute", outputs = { @Output(Outputs.RETURN_CODE), @Output(Outputs.RETURN_RESULT), @Output(Outputs.EXCEPTION) }, responses = { @Response(text = Outputs.SUCCESS, field = ...
java
public static LoaderPipe getPipe(String name, android.support.v4.app.Fragment fragment, Context applicationContext) { Pipe pipe = pipes.get(name); LoaderAdapter adapter = new LoaderAdapter(fragment, applicationContext, pipe, name); adapter.setLoaderIds(loaderIdsForNamed); return adapter;...
java
private void calculateHighestAlert() { synchronized (alerts) { highestAlert = null; for (Alert alert : alerts) { if (isHighestAlert(alert)) { highestAlert = alert; } } calculateHighestAlert = false; ...
python
def _free(self, ptr): """ Handler for any libc `free` SimProcedure call. If the heap has faithful support for `free`, it ought to be implemented in a `free` function (as opposed to the `_free` function). :param ptr: the location in memory to be freed """ raise NotImpleme...
python
def from_bytes(cls, bitstream, decode_payload=True): r''' Parse the given packet and update properties accordingly >>> data_hex = ('c033d3c10000000745c0005835400000' ... 'ff06094a254d38204d45d1a30016f597' ... 'a1c3c7406718bf1b50180ff0793f0000' ......
python
def get_symbol_at_address(self, address): """ Tries to find the closest matching symbol for the given address. @type address: int @param address: Memory address to query. @rtype: None or tuple( str, int, int ) @return: Returns a tuple consisting of: - Name...
python
def parse_email(self): """Email address parsing is done in several stages. First the name of the email use is determined. Then it looks for a '@' as a delimiter between the name and the site. Lastly the email site is matched. Each part's string is stored, combined and returned. ...
python
def copy(self, name=None, prefix=None): """A copy of this :class:`Config` container. If ``prefix`` is given, it prefixes all non :ref:`global settings <setting-section-global-server-settings>` with it. Used when multiple applications are loaded. """ cls = self.__class__ ...
java
@Deprecated public static Delay constant(int delay, TimeUnit timeUnit) { LettuceAssert.notNull(timeUnit, "TimeUnit must not be null"); return constant(Duration.ofNanos(timeUnit.toNanos(delay))); }
python
def _contains_value(self, value): """Helper function for __contains__ to check a single value is contained within the interval""" g = operator.gt if self._lower is self.OPEN else operator.ge l = operator.lt if self._upper is self.OPEN else operator.le return g(value, self.lower_value) an...
python
def change_default( kls, key, new_default, new_converter=None, new_reference_value=None, ): """return a new configman Option object that is a copy of an existing one, giving the new one a different default value""" an_option = kls.get_required_config()[key].copy() an_option.default =...
java
public Classifier<L, F> trainClassifierSemiSup(GeneralDataset<L, F> data, GeneralDataset<L, F> biasedData, double[][] confusionMatrix, double[] initial) { double[][] weights = trainWeightsSemiSup(data, biasedData, confusionMatrix, initial); LinearClassifier<L, F> classifier = new LinearClassifier<L, F>(weigh...
java
public void setEditorTarget (PropertyEditorTarget target) { if (target instanceof DBMetaColumnNode) { super.setEditorTarget(target); this.tfColumnName.setText((String)target.getAttribute(DBMetaColumnNode.ATT_COLUMN_NAME)); } else { ...
java
public void run() throws IllegalArgumentException { List<List<ResultEntry>> groups = null; for (int i = 0; i < this.repeatedRuns; ++i) { this.solver.getResult().clearResults(); this.solver.run(); Result result = this.solver.getResult(); if (groups == nul...
python
def remove_enclosure(self, left_char, right_char): """ Remove enclosure pair from set of enclosures. :param str left_char: left character of enclosure pair - e.g. "(" :param str right_char: right character of enclosure pair - e.g. ")" """ assert len(left_char) == 1, \ ...
java
static <K,V> TreeMapEntry<K,V> predecessor(TreeMapEntry<K,V> t) { if (t == null) return null; else if (t.left != null) { TreeMapEntry<K,V> p = t.left; while (p.right != null) p = p.right; return p; } else { TreeMapEntry<...
java
ByteString getState(String channelId, String txId, String collection, String key) { return invokeChaincodeSupport(newGetStateEventMessage(channelId, txId, collection, key)); }
java
private int getTotal(Class<?> clazz) { StringBuilder sql = new StringBuilder(); sql.append(SQLUtils.getSelectCountSQL(clazz)); sql.append(SQLUtils.autoSetSoftDeleted("", clazz)); log(sql); long start = System.currentTimeMillis(); int rows = jdbcTemplate.queryForOb...
python
def new_encoded_stream(args, stream): '''Return a stream writer.''' if args.ascii_print: return wpull.util.ASCIIStreamWriter(stream) else: return stream
java
public ProjectTimeFormat getTimeFormat(int field) { ProjectTimeFormat result; if ((field < m_fields.length) && (m_fields[field].length() != 0)) { result = ProjectTimeFormat.getInstance(Integer.parseInt(m_fields[field])); } else { result = ProjectTimeFormat.TWELV...
python
def replace(self, s, data, attrs=None): """ Replace the attributes of the plotter data in a string %(replace_note)s Parameters ---------- s: str String where the replacements shall be made data: InteractiveBase Data object from which to u...
java
public static boolean isString( Object obj ) { if( (obj instanceof String) || (obj instanceof Character) || (obj != null && (obj.getClass() == Character.TYPE || String.class.isAssignableFrom( obj.getClass() ))) ){ return true; } return false; }
python
def _setup_chassis(self): """ Sets up the router with the corresponding chassis (create slots and insert default adapters). """ self._create_slots(2) self._slots[0] = self.integrated_adapters[self._chassis]()
java
@Nonnull @Override public AffinityGroup get(@Nonnull String affinityGroupId) throws InternalException, CloudException { if(affinityGroupId == null || affinityGroupId.isEmpty()) throw new InternalException("Please specify the id for the affinity group you want to retrieve."); AzureMe...
python
def launch_gateway(conf=None, popen_kwargs=None): """ launch jvm gateway :param conf: spark configuration passed to spark-submit :param popen_kwargs: Dictionary of kwargs to pass to Popen when spawning the py4j JVM. This is a developer feature intended for use in customizing how pyspark ...
java
public static double getScaleFactor(IAtomContainer container, double bondLength) { double currentAverageBondLength = getBondLengthAverage(container); if (currentAverageBondLength == 0 || Double.isNaN(currentAverageBondLength)) return 1; return bondLength / currentAverageBondLength; }
python
def generate_value_label(self, byteorder, encoding): """ Parameters ---------- byteorder : str Byte order of the output encoding : str File encoding Returns ------- value_label : bytes Bytes containing the formatted val...
java
private static double doubleHighPart(double d) { if (d > -Precision.SAFE_MIN && d < Precision.SAFE_MIN){ return d; // These are un-normalised - don't try to convert } long xl = Double.doubleToLongBits(d); xl = xl & MASK_30BITS; // Drop low order bits return Double.lon...
java
public DeregisterInstancesFromLoadBalancerRequest withInstances(Instance... instances) { if (this.instances == null) { setInstances(new com.amazonaws.internal.SdkInternalList<Instance>(instances.length)); } for (Instance ele : instances) { this.instances.add(ele); ...
python
def assign(self, attrs): """Merge new attributes """ for k, v in attrs.items(): setattr(self, k, v)
python
def list_external_tools_courses(self, course_id, include_parents=None, search_term=None, selectable=None): """ List external tools. Returns the paginated list of external tools for the current context. See the get request docs for a single tool for a list of properties on an extern...
python
def chunks(data, chunk_size): """ Yield chunk_size chunks from data.""" for i in xrange(0, len(data), chunk_size): yield data[i:i+chunk_size]
python
def get_property(self, key): """Returns the value of the network attachment property with the given name. If the requested data @a key does not exist, this function will succeed and return an empty string in the @a value argument. in key of type str Name of the prop...
python
def setup_callbacks(self): ''' Assign attributes for pygit2 callbacks ''' if PYGIT2_VERSION >= _LooseVersion('0.23.2'): self.remotecallbacks = pygit2.RemoteCallbacks( credentials=self.credentials) if not self.ssl_verify: # Override ...
python
def load_mode(node): """Load one observing mdode""" obs_mode = ObservingMode() obs_mode.__dict__.update(node) # handle validator load_mode_validator(obs_mode, node) # handle builder load_mode_builder(obs_mode, node) # handle tagger: load_mode_tagger(obs_mode, node) return obs...
python
def bna_config_cmd_output_session_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") bna_config_cmd = ET.Element("bna_config_cmd") config = bna_config_cmd output = ET.SubElement(bna_config_cmd, "output") session_id = ET.SubElement(output,...
java
public void marshall(JobFlowInstancesConfig jobFlowInstancesConfig, ProtocolMarshaller protocolMarshaller) { if (jobFlowInstancesConfig == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(jobFlowInstan...
java
public void uncheck() { getDispatcher().beforeUncheck(this); RemoteWebElement e = (RemoteWebElement) getElement(); while (e.isSelected()) { e.click(); } if (Config.getBoolConfigProperty(ConfigProperty.ENABLE_GUI_LOGGING)) { logUIAction(UIActions.U...
java
public EtcdResponse put(final String key, final String value) throws EtcdException { UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(KEYSPACE); builder.pathSegment(key); MultiValueMap<String, String> payload = new LinkedMultiValueMap<>(1); payload.set("value", value); return execute(builde...
java
static void verifyItemDoesNotAlreadyExist(@Nonnull ItemGroup<?> parent, @Nonnull String newName, @CheckForNull Item variant) throws IllegalArgumentException, Failure { Item existing; try (ACLContext ctxt = ACL.as(ACL.SYSTEM)) { existing = parent.getItem(newName); } if (existi...
java
private Collection<ClassDoc> subclasses(ClassDoc cd) { Collection<ClassDoc> ret = classToSubclass.get(cd.qualifiedName()); if (ret == null) { ret = new TreeSet<ClassDoc>(); List<ClassDoc> subs = classtree.subclasses(cd); if (subs != null) { ret.addAll(...
java
public static void copy(InputStream in, File file) throws IOException { OutputStream out = new BufferedOutputStream(new FileOutputStream(file)); try { IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(out); } }
java
void addSubsystem(final OperationTransformerRegistry registry, final String name, final ModelVersion version) { final OperationTransformerRegistry profile = registry.getChild(PathAddress.pathAddress(PROFILE)); final OperationTransformerRegistry server = registry.getChild(PathAddress.pathAddress(HOST, SE...
java
private void prepareProperties(QName portQName, Map<String, String> serviceRefProps, Map<String, String> portProps) throws IOException { // Merge the properties form port and service. Map<String, String> allProperties = new HashMap<String, String>(); if (null != serviceRefProps) { a...
java
@Override public boolean containsAll(Collection<?> collection) { for (Object nextCandidateElement : collection) { if (!contains(nextCandidateElement)) { return false; } } return true; }
java
public TouchActions singleTap(WebElement onElement) { if (touchScreen != null) { action.addAction(new SingleTapAction(touchScreen, (Locatable) onElement)); } tick(touchPointer.createPointerDown(0)); tick(touchPointer.createPointerUp(0)); return this; }
python
def generate(variables, templates_path, main_template): """ :Parameters: variables : dict Template parameters, passed through. templates_path : str Root directory for transclusions. main_template : str Contents of the main template. Returns the re...
python
def _add_pos1(token): """ Adds a 'pos1' element to a frog token. """ result = token.copy() result['pos1'] = _POSMAP[token['pos'].split("(")[0]] return result
python
def read_group_info(self): """Get information about groups directly from the widget.""" self.groups = [] for i in range(self.tabs.count()): one_group = self.tabs.widget(i).get_info() # one_group['name'] = self.tabs.tabText(i) self.groups.append(one_group)
python
def re_acquire_lock(self, ltime=5): '''Re-acquire the lock. You must already own the lock; this is best called from within a :meth:`lock` block. :param int ltime: maximum time (in seconds) to own lock :return: the session lock identifier :raise rejester.exceptions.Envir...
python
def _get_df(self): """Returns stellar model grid with desired bandpasses and with standard column names bands must be iterable, and are parsed according to :func:``get_band`` """ grids = {} df = pd.DataFrame() for bnd in self.bands: s,b = self.get_band(bnd, *...
java
public static Optional<LineageInfo> getLineageInfo(@Nullable SharedResourcesBroker<GobblinScopeTypes> broker) { if (broker == null) { log.warn("Null broker. Will not track data lineage"); return Optional.absent(); } try { LineageInfo lineageInfo = broker.getSharedResource(new LineageInfoF...
java
public int getMaxEndPosition(int docId, int position) throws IOException { if (ignoreSpans != null && docId == currentDocId) { if (position < minimumPosition) { throw new IOException( "Unexpected position, should be >= " + minimumPosition + "!"); } computeFullEndPositionList(po...
java
private void executeJoinRequest(JoinRequest joinRequest, Connection connection) { clusterServiceLock.lock(); try { if (checkJoinRequest(joinRequest, connection)) { return; } if (!authenticate(joinRequest)) { return; } ...
java
public Observable<Page<CertificateInner>> listByAutomationAccountNextAsync(final String nextPageLink) { return listByAutomationAccountNextWithServiceResponseAsync(nextPageLink) .map(new Func1<ServiceResponse<Page<CertificateInner>>, Page<CertificateInner>>() { @Override ...
python
def _deserialize(cls, key, value, fields): """ Marshal incoming data into Python objects.""" converter = cls._get_converter_for_field(key, None, fields) return converter.deserialize(value)
java
public void marshall(GameSessionPlacement gameSessionPlacement, ProtocolMarshaller protocolMarshaller) { if (gameSessionPlacement == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(gameSessionPlacemen...
python
def get_slot_position(self, container, type='a'): """Returns the slot where the analyses from the type and container passed in are located within the worksheet. :param container: the container in which the analyses are grouped :param type: type of the analysis :return: the slot ...
java
<T> T _deserialize(String body, Class<T> clazz) { if(body == null || body.isEmpty()){ throw new ServiceException(ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR, ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR.getMessageTemplate(), "the message body is empty"); } ...
java
public void marshall(ReviewPolicy reviewPolicy, ProtocolMarshaller protocolMarshaller) { if (reviewPolicy == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(reviewPolicy.getPolicyName(), POLICYNAME_BI...
python
def order_by_refs(envs): """ Return topologicaly sorted list of environments. I.e. all referenced environments are placed before their references. """ topology = { env['name']: set(env['refs']) for env in envs } by_name = { env['name']: env for env in envs ...
java
public static String getString(String key) { try { return RESOURCE_BUNDLE.getString(key); } catch (MissingResourceException e) { return '!' + key + '!'; } }
java
public void doEdit(@FormGroup("nodeInfo") Group nodeInfo, @FormGroup("nodeParameterInfo") Group nodeParameterInfo, @Param("pageIndex") int pageIndex, @Param("searchKey") String searchKey, @FormField(name = "formNodeError", group = "nodeInfo") CustomErrors err, Navigator nav...
java
public void addExpression() { SWRL expression = getOWLModel().createSWRLExpression(null); if (getOWLValueObject().owlValue().isIndividual()) { SWRLIndividual swrlIndividual = swrl().wrapIndividual(getOWLValueObject().owlValue().castTo(OWLIndividual.class)); Atom atom = swrl().cre...
python
def install_package_command(package_name): '''install python package from pip''' #TODO refactor python logic if sys.platform == "win32": cmds = 'python -m pip install --user {0}'.format(package_name) else: cmds = 'python3 -m pip install --user {0}'.format(package_name) call(cmds, she...
python
def _execute_autoprops_on_class(object_type, # type: Type[T] include=None, # type: Union[str, Tuple[str]] exclude=None # type: Union[str, Tuple[str]] ): """ This method will automatically add one getter and one ...
python
def im_open(self, *, user: str, **kwargs) -> SlackResponse: """Opens a direct message channel. Args: user (str): The user id to open a DM with. e.g. 'W1234567890' """ kwargs.update({"user": user}) return self.api_call("im.open", json=kwargs)