language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public SipCall makeCall(String to, String viaNonProxyRoute) { return makeCall(to, viaNonProxyRoute, null, null, null); }
python
def maximum_size_estimated(self): """ Get the CoRE Link Format sz attribute of the resource. :return: the CoRE Link Format sz attribute """ value = "sz=" lst = self._attributes.get("sz") if lst is None: value = "" else: value += "\...
java
public static void localiseButton(AbstractButton button, String key, String defaultString, boolean setMnemonic) { AnnotatedString as = new AnnotatedString(L10N.getLocalString(key, defaultString)); button.setText(as.toString()); int mnemonic; if (setMnemonic && (mnemonic = as.getMnemonic(...
java
static TokenLifeCycleManager getInstance(final String iamEndpoint, final String apiKey) { if (iamEndpoint == null || iamEndpoint.isEmpty()) { throw new IllegalArgumentException( "Cannot initialize with null or empty IAM endpoint."); } if (apiKey == nul...
java
public void setId3Insertions(java.util.Collection<Id3Insertion> id3Insertions) { if (id3Insertions == null) { this.id3Insertions = null; return; } this.id3Insertions = new java.util.ArrayList<Id3Insertion>(id3Insertions); }
java
public SimpleFormatter getByVariant(CharSequence variant) { assert isValid(); int idx = StandardPlural.indexOrOtherIndexFromString(variant); SimpleFormatter template = templates[idx]; return (template == null && idx != StandardPlural.OTHER_INDEX) ? templates[StandardPlura...
java
@Override public DeleteRoleAliasResult deleteRoleAlias(DeleteRoleAliasRequest request) { request = beforeClientExecution(request); return executeDeleteRoleAlias(request); }
java
public void addAndLinkChild(AbstractPlanNode child) { assert(child != null); m_children.add(child); child.m_parents.add(this); }
python
def read(self, filehandle): """Read JSON from `filehandle`.""" return self.__import(json.load(filehandle, **self.kwargs))
python
def parse_args(): '''Definite the arguments users need to follow and input''' parser = argparse.ArgumentParser(prog='nnictl', description='use nnictl command to control nni experiments') parser.add_argument('--version', '-v', action='store_true') parser.set_defaults(func=nni_info) # create subparse...
python
def new_record(self, key, value): """Populate the ``new_record`` key. Also populates the ``ids`` key through side effects. """ new_record = self.get('new_record', {}) ids = self.get('ids', []) for value in force_list(value): for id_ in force_list(value.get('a')): ids.append...
java
void domainCommandString(StringBuilder buf, String uri, MCMPAction status, String lbgroup) { switch (status) { case ENABLE: buf.append("<a href=\"" + uri + "?" + getNonce() + "&Cmd=ENABLE-APP&Range=DOMAIN&Domain=" + lbgroup + "\">Enable Nodes</a> "); break; ...
python
def declare_queues(self, queues): """ Declare a list of queues. Args: queues (list of dict): A list of dictionaries, where each dictionary represents an exchange. Each dictionary can have the following keys: * queue (str): The name of the queue ...
python
def build_tag(self, tag, text='', attrs=None): r"""Build tag full info include the attributes. :param tag: tag name. :param text: tag text. :param attrs: tag attributes. Default:``None``. :type attrs: dict or None :rtype: str """ return '%s%s%s' % (self.t...
java
private static boolean needSecondRoundTermvector( List<ComponentTermVector> termVectorList) throws IOException { boolean needSecondRound = false; for (ComponentTermVector termVector : termVectorList) { if (!termVector.full && termVector.list == null) { boolean doCheck; doCheck = term...
python
def getCompleteFreqs(blastHits): """ Make a dictionary which collects all mutation frequencies from all reads. Calls basePlotter to get dotAlignment, which is passed to getAPOBECFrequencies with the respective parameter, to collect the frequencies. @param blastHits: A L{dark.blast.BlastHits...
java
public String getComparatorType() { StringBuilder sb = new StringBuilder(); sb.append("CompositeType("); sb.append(StringUtils.join( Collections2.transform(components, new Function<FieldMapper<?>, String>() { public String apply(FieldMapper<?> input) { ...
python
def _memory_usage(self, pid='self', category="hwm", container=None): """ Memory usage of the process in kilobytes. :param str pid: Process ID of process to check :param str category: Memory type to check. 'hwm' for high water mark. """ if container: # TODO: P...
java
private Map<String, DecimalFormat.Unit[]> otherPluralVariant(Map<String, String[][]> pluralCategoryToPower10ToAffix, long[] divisor, Collection<String> debugCreationErrors) { // check for bad divisors if (divisor.length < CompactDecimalDataCache.MAX_DIGITS) { recordError(debugCr...
python
def highlight_text(self, text, start, end): """ Highlights given text. :param text: Text. :type text: QString :param start: Text start index. :type start: int :param end: Text end index. :type end: int :return: Method success. :rtype: bool...
python
def print_params(self): """Print the current best set of parameters""" print("Parameters") print("--------------------") for param in PARAM_ORDER: print(' {:>11s} = {}'.format(param, self.parameter[param]))
java
public FileMetaData input(int which, int i) { checkArgument(which == 0 || which == 1, "which must be either 0 or 1"); if (which == 0) { return levelInputs.get(i); } else { return levelUpInputs.get(i); } }
java
public static String getFilenameExtension(String path) { if (path == null) { return null; } int extIndex = path.lastIndexOf("."); if (extIndex == -1) { return null; } return path.substring(extIndex + 1); }
java
public static Properties properties(CSProperties p) { Properties pr = new Properties(); pr.putAll(p); return pr; }
python
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values. """ assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES ...
java
@Nullable public static Double parseDoubleObj (@Nullable final Object aObject, @Nullable final Double aDefault) { final double dValue = parseDouble (aObject, Double.NaN); return Double.isNaN (dValue) ? aDefault : Double.valueOf (dValue); }
java
void appendSubRules( String[] parentSelector, CssFormatter formatter ) { try { if( important ) { formatter.incImportant(); } for( MixinMatch match : getRules( formatter ) ) { Rule rule = match.getRule(); formatter.addMixin( rule...
python
def header_length(header): """Calculates the ciphertext message header length, given a complete header. :param header: Complete message header object :type header: aws_encryption_sdk.structures.MessageHeader :rtype: int """ # Because encrypted data key lengths may not be knowable until the ciph...
python
def set_journal_comment(self, comment): """Sets a comment. arg: comment (string): the new comment raise: InvalidArgument - ``comment`` is invalid raise: NoAccess - ``Metadata.isReadonly()`` is ``true`` raise: NullArgument - ``comment`` is ``null`` *compliance: mand...
python
def lock(self): """Returns a JSON representation of the Pipfile.""" data = self.data data['_meta']['hash'] = {"sha256": self.hash} data['_meta']['pipfile-spec'] = 6 return json.dumps(data, indent=4, separators=(',', ': '))
python
def _group_events(catalog, process_len, template_length, data_pad): """ Internal function to group events into sub-catalogs based on process_len. :param catalog: Catalog to groups into sub-catalogs :type catalog: obspy.core.event.Catalog :param process_len: Length in seconds that data will be proce...
python
def isAncestorOf(self, other): '''Returns whether this Key is an ancestor of `other`. >>> john = Key('/Comedy/MontyPython/Actor:JohnCleese') >>> Key('/Comedy').isAncestorOf(john) True ''' if isinstance(other, Key): return other._string.startswith(self._string + '/') raise...
python
def config_at(self, i): """Gets the ith config""" selections = {} for key in self.store: value = self.store[key] if isinstance(value, list): selected = i % len(value) i = i // len(value) selections[key]= value[selected] else: sele...
java
public void texture(Shape shape, Image image, float scaleX, float scaleY) { texture(shape, image, scaleX, scaleY, false); }
python
def check_params_types(self, method): '''Types in argument annotations must be instances, not classes.''' mn = method.__name__ annos = dict(method.__annotations__) errors = [] # Take a look at the syntax msg_tuple = 'Parameter {} in method {} is not annotated with a tuple...
java
public com.google.javascript.jscomp.RequirementOrBuilder getRequirementOrBuilder( int index) { return requirement_.get(index); }
java
public WikiPage createPage(Object projectIdOrPath, String title, String content) throws GitLabApiException { // one of title or content is required GitLabApiForm formData = new GitLabApiForm() .withParam("title", title) .withParam("content", content); Response re...
python
def _set_proxy_headers(self, url, headers=None): """ Sets headers needed by proxies: specifically, the Accept and Host headers. Only sets headers not provided by the user. """ headers_ = {'Accept': '*/*'} netloc = parse_url(url).netloc if netloc: head...
python
def matrix_undirected_weighted(user, interaction=None): """ Returns an undirected, weighted matrix for call, text and call duration where an edge exists if the relationship is reciprocated. """ matrix = _interaction_matrix(user, interaction=interaction) result = [[0 for _ in range(len(matrix))] ...
java
public PublicIPPrefixInner getByResourceGroup(String resourceGroupName, String publicIpPrefixName, String expand) { return getByResourceGroupWithServiceResponseAsync(resourceGroupName, publicIpPrefixName, expand).toBlocking().single().body(); }
java
@Override public ResourceSet<SyncStream> read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); }
python
def get_remote_user(request): """Parse basic HTTP_AUTHORIZATION and return user name """ if 'HTTP_AUTHORIZATION' not in request.environ: return authorization = request.environ['HTTP_AUTHORIZATION'] try: authmeth, auth = authorization.split(' ', 1) except ValueError: # not enoug...
java
private static void downloadFileHandleRedirect(Context context, String fromUrl, File toFile, int redirect, DownloadProgressListener listener, DownloadCancelListener cancelListener) throws IOException { if (context == null) { throw new RuntimeException("Context shall not be null"); } if (!already...
python
def is_child_of_repository(self, id_, repository_id): """Tests if a node is a direct child of another. arg: id (osid.id.Id): an ``Id`` arg: repository_id (osid.id.Id): the ``Id`` of a repository return: (boolean) - ``true`` if the ``id`` is a child of ``repository_...
java
@PostMapping("/setting/upload/json") public void uploadSetting(HttpServletRequest req) { this.validationSessionComponent.sessionCheck(req); this.msgSettingService.updateValidationData((MultipartHttpServletRequest) req); }
python
def install_plugin(username, repo): """Installs a Blended plugin from GitHub""" print("Installing plugin from " + username + "/" + repo) pip.main(['install', '-U', "git+git://github.com/" + username + "/" + repo + ".git"])
java
@Override public String initValuesImpl(final FieldCase c) { if (c == FieldCase.NULL) { return null; } String value = source.initValues(c); if (value == null) { return defaultValue; } return value; }
python
def wxcode(code: str) -> str: """ Translates weather codes into readable strings Returns translated string of variable length """ if not code: return '' ret = '' if code[0] == '+': ret = 'Heavy ' code = code[1:] elif code[0] == '-': ret = 'Light ' ...
java
public void setNetworkProfiles(java.util.Collection<NetworkProfile> networkProfiles) { if (networkProfiles == null) { this.networkProfiles = null; return; } this.networkProfiles = new java.util.ArrayList<NetworkProfile>(networkProfiles); }
java
protected ID convertCookieUserKeyToUserId(String userKey) { final ID userId; try { userId = toTypedUserId(userKey); // as default (override if it needs) } catch (NumberFormatException e) { throw new LoginFailureException("Invalid user key (not ID): " + userKey, e); ...
java
@Override public long getStreamSegmentId(String streamSegmentName, boolean updateLastUsed) { synchronized (this.lock) { StreamSegmentMetadata metadata = this.metadataByName.getOrDefault(streamSegmentName, null); if (updateLastUsed && metadata != null) { metadata.setLa...
python
def get_friends(self, username, offset=0, limit=10): """Get the users list of friends :param username: The username you want to get a list of friends of :param offset: the pagination offset :param limit: the pagination limit """ response = self._req('/user/friends/{}'....
python
def _set_star_value(star_code, number_stars): """ Internal function that is used for update the number of active stars (that define notebook difficulty level) ---------- Parameters ---------- star_code : str String with the HTML code to be changed. number_stars : int Nu...
java
public static Condition createCondition(String expression) { try { return INSTANCE.ctorCondition.newInstance(expression); } catch (Exception e) { throw new RuntimeException(e); } }
python
def normalize_url(url): """ Normalize url """ if not url: return url matched = _windows_path_prefix.match(url) if matched: return path2url(url) p = six.moves.urllib.parse.urlparse(url) if p.scheme == '': if p.netloc == '' and p.path != '': # it should be...
python
def handle_namespace_invalid(self, line: str, position: int, tokens: ParseResults) -> None: """Raise an exception when parsing a name missing a namespace.""" name = tokens[NAME] raise NakedNameWarning(self.get_line_number(), line, position, name)
python
def _tokenize(self, text): """Tokenizes a piece of text.""" text = self._clean_text(text) # This was added on November 1st, 2018 for the multilingual and Chinese # models. This is also applied to the English models now, but it doesn't # matter since the English models were not t...
python
def search_prefix(self, auth, query, search_options=None): """ Search prefix list for prefixes matching `query`. * `auth` [BaseAuth] AAA options. * `query` [dict_to_sql] How the search should be performed. * `search_options` [options_dict] ...
java
public boolean addAnnotationInfo(int indent, Element element, VariableElement param, Content tree) { return addAnnotationInfo(indent, element, param.getAnnotationMirrors(), false, tree); }
python
def connect_hgroup(self, hgroup, volume, **kwargs): """Create a shared connection between a host group and a volume. :param hgroup: Name of hgroup to connect to volume. :type hgroup: str :param volume: Name of volume to connect to hgroup. :type volume: str :param \*\*kwa...
java
private void parse(int msgStart, String source, ParsePosition pos, Object[] args, Map<String, Object> argsMap) { if (source == null) { return; } String msgString=msgPattern.getPatternString(); int prevIndex=msgPattern.getPart(msgStart).getLimit(); ...
java
public TerminalResult BR_OPEN() { ConcatenateExpression ce = new ConcatenateExpression(Concatenator.BR_OPEN); this.astObjectsContainer.addAstObject(ce); TerminalResult ret = APIAccess.createTerminalResult(ce); QueryRecorder.recordInvocation(this, "BR_OPEN", ret); return ret; }
python
def refresh_config(self): ''' __NB__ This *must* be called from a *different* thread than the GUI/Gtk thread. ''' from gi.repository import Clutter, Gst, GstVideo, ClutterGst from path_helpers import path from .warp import bounding_box_from_allocation if self.con...
java
public static WriteFuture newNotWrittenFuture(IoSession session, Throwable cause) { DefaultWriteFuture unwrittenFuture = new DefaultWriteFuture(session); unwrittenFuture.setException(cause); return unwrittenFuture; }
python
def pipe_numberinput(context=None, _INPUT=None, conf=None, **kwargs): """An input that prompts the user for a number and yields it forever. Not loopable. Parameters ---------- context : pipe2py.Context object _INPUT : not used conf : { 'name': {'value': 'parameter name'}, 'p...
java
private void writeJsonForArchive(PrintWriter wrt, List<RecentJobEvent> jobs) { wrt.write("["); // sort jobs by time Collections.sort(jobs, new Comparator<RecentJobEvent>() { @Override public int compare(RecentJobEvent o1, RecentJobEvent o2) { if(o1.getTimestamp() < o2.getTimestamp()) { retur...
java
protected int addKey(String k) { Integer rv = rkeys.get(k); if (rv == null) { rv = generateOpaque(); keys.put(rv, k); bkeys.put(rv, KeyUtil.getKeyBytes(k)); rkeys.put(k, rv); synchronized (vbmap) { vbmap.put(k, new Short((short) 0)); } } return rv; }
java
protected TimeZone guessTimeZone() { // TODO fix using real data // for single-zone countries, pick that zone // for others, pick the most populous zone // for now, just use fixed value // NOTE: in a few cases can do better by looking at language. // Eg haw+US should go t...
python
def time2string(tstamp, micro=True): """Given a :class:`datetime.datetime` object, return a formatted time string.""" tformat = TIME_FORMAT if micro else TIME_FORMAT[:-len(MICRO)] return tstamp.strftime(tformat)
java
private void placeMultipleGroups(IAtomContainer mol) { final List<Sgroup> sgroups = mol.getProperty(CDKConstants.CTAB_SGROUPS); if (sgroups == null) return; final List<Sgroup> multipleGroups = new ArrayList<>(); for (Sgroup sgroup : sgroups) { if (sgroup.getType()...
java
private void readChunk() throws IOException { if (mDataReader == null) { mDataReader = mDataReaderFactory.create(mPos, mLength - mPos); } if (mCurrentChunk != null && mCurrentChunk.readableBytes() == 0) { mCurrentChunk.release(); mCurrentChunk = null; } if (mCurrentChunk == null) ...
python
def psaux(name): ''' Retrieve information corresponding to a "ps aux" filtered with the given pattern. It could be just a name or a regular expression (using python search from "re" module). CLI Example: .. code-block:: bash salt '*' ps.psaux www-data.+apache2 ''' sanitize_nam...
java
private static Observable<List<File>> createFilesFromClipData(final Context context, final ClipData clipData, final MimeMap mimeTypeMap) { return Observable.defer(new Func0<Observable<List<File>>>() { @Override public Observable<List<File>> call() { int numOfUris = clipData.getItemCount();...
java
public static Pair<Integer, Integer> parseResolution(@NonNull final Context context, @NonNull final String resolution) { Condition.INSTANCE.ensureNotNull(context, "The context may not be null"); Condition.INSTANCE.ensureNotNull(resolution, "The re...
python
def connect(self, creds): """Return a boto S3Connection set up with great care. This includes TLS settings, calling format selection, and region detection. The credentials are applied by the caller because in many cases (instance-profile IAM) it is possible for those cr...
python
def set_body_files(context): """ Parameters: +-------------+--------------+ | param_name | path_to_file | +=============+==============+ | param1 | value1 | +-------------+--------------+ | param2 | value2 | +-------------+---------...
python
def FromBinary(cls, record_data, record_count=1): """Create an UpdateRecord subclass from binary record data. This is a multi-action record that matches a pattern of error checking RPC calls: begin config push config data <possibly multiple> end config A...
python
def remove_child(self, router): '''remove a :class:`Router` from the :attr:`routes` list.''' if router in self.routes: self.routes.remove(router) router._parent = None
python
def flatten(d, parent_key='', separator='__'): """ Flatten a nested dictionary. Parameters ---------- d: dict_like Dictionary to flatten. parent_key: string, optional Concatenated names of the parent keys. separator: string, optional Separator between the names of th...
java
@Override public void clear(final Class<?> clas) { this.logger.debug("@clear:".concat(clas.getName())); getCachableMap(clas).clear(); }
java
public com.google.api.ads.adwords.axis.v201809.cm.FeedItemTargetType getTargetType() { return targetType; }
java
private void obtainHeaderDividerColor(@StyleRes final int themeResourceId) { TypedArray typedArray = getContext().getTheme().obtainStyledAttributes(themeResourceId, new int[]{R.attr.materialDialogHeaderDividerColor}); int defaultColor = ContextCompat.getColor(getContext(), R.color.header...
java
private void init(final Task<Revision> task) { this.partCounter++; this.result = new Task<Diff>(task.getHeader(), partCounter); }
python
def mass_send_message(self, msg): """Send a message to all connected clients. Notes ----- This method can only be called in the IOLoop thread. """ for stream in self._connections.keys(): if not stream.closed(): # Don't cause noise by trying t...
python
def Tracer_CMFR_N(t_seconds, t_bar, C_bar, N): """Used by Solver_CMFR_N. All inputs and outputs are unitless. This is The model function, f(x, ...). It takes the independent variable as the first argument and the parameters to fit as separate remaining arguments. :param t_seconds: List of times :ty...
python
def check_is_working(self): """ Returns True if the wash alert web interface seems to be working properly, or False otherwise. >>> l.check_is_working() """ try: r = requests.post("http://{}/".format(LAUNDRY_DOMAIN), timeout=60, data={ "locationid": "5...
java
public static JsonArray getArray(JsonObject object, String field, JsonArray defaultValue) { final JsonValue value = object.get(field); if (value == null || value.isNull()) { return defaultValue; } else { return value.asArray(); } }
python
def warn(self, message, container=None): """Present the warning `message` to the user, adding information on the location of the related element in the input file.""" if self.source is not None: message = '[{}] '.format(self.source.location) + message if container is not None...
python
def get_all(self, keys): """ Returns the entries for the given keys. **Warning: The returned map is NOT backed by the original map, so changes to the original map are NOT reflected in the returned map, and vice-versa.** **Warning 2: This method uses __hash__ and __eq__ ...
python
def qteNextApplet(self, numSkip: int=1, ofsApp: (QtmacsApplet, str)=None, skipInvisible: bool=True, skipVisible: bool=False, skipMiniApplet: bool=True, windowObj: QtmacsWindow=None): """ Return the next applet in cyclic order. If...
java
public void addNewInstanceMethod(Method method) { final CachedMethod cachedMethod = CachedMethod.find(method); NewInstanceMetaMethod newMethod = new NewInstanceMetaMethod(cachedMethod); final CachedClass declaringClass = newMethod.getDeclaringClass(); addNewInstanceMethodToIndex(newMetho...
java
private double epsilon(Front front, Front referenceFront) throws JMetalException { double eps, epsJ = 0.0, epsK = 0.0, epsTemp; int numberOfObjectives = front.getPointDimensions() ; eps = Double.MIN_VALUE; for (int i = 0; i < referenceFront.getNumberOfPoints(); i++) { for (int j = 0; j < front...
python
def plot_bargraph( self, rank="auto", normalize="auto", top_n="auto", threshold="auto", title=None, xlabel=None, ylabel=None, tooltip=None, return_chart=False, haxis=None, legend="auto", label=None, ): ""...
python
def cache_instrument_models(self): """ Queries Smoothie for the model and ID strings of attached pipettes, and saves them so they can be reported without querying Smoothie again (as this could interrupt a command if done during a run or other movement). Shape of return dict shou...
python
def filter(self, displayed=False, enabled=False): """ Filter elements by visibility and enabled status. :param displayed: whether to filter out invisible elements :param enabled: whether to filter out disabled elements Returns: an :class:`ElementSelector` """ i...
java
public XObject execute(XPathContext xctxt) throws javax.xml.transform.TransformerException { XNodeSet iter = new XNodeSet((LocPathIterator)m_clones.getInstance()); iter.setRoot(xctxt.getCurrentNode(), xctxt); return iter; }
python
def read(self, entity=None, attrs=None, ignore=None, params=None): """Work around a bug. Rename ``search`` to ``search_``. For more information on the bug, see `Bugzilla #1257255 <https://bugzilla.redhat.com/show_bug.cgi?id=1257255>`_. """ if attrs is None: attrs = ...
java
public static Class<?>[] buildArgumentClasses( Object... arguments ) { if (arguments == null || arguments.length == 0) return EMPTY_CLASS_ARRAY; Class<?>[] result = new Class<?>[arguments.length]; int i = 0; for (Object argument : arguments) { if (argument != null) { ...
python
def run_simulations(self, param_list, show_progress=True): """ Run several simulations specified by a list of parameter combinations. Note: this function does not verify whether we already have the required simulations in the database - it just runs all the parameter combination...
python
def evaluate(self, x, y, x_derivative=0, smooth=0, simple='auto'): """ this evaluates the 2-d spline by doing linear interpolation of the curves """ if simple=='auto': simple = self.simple # find which values y is in between for n in range(0, len(self.y_va...