language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
final TrmMessage createInboundTrmMessage(JsMsgObject jmo, int messageType) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())SibTr.entry(tc, "createInboundTrmMessage " + messageType ); TrmMessage trmMessage = null; /* Create an instance of the appropriate message subclass ...
python
def _workout_filename(filename): ''' Recursively workout the file name from an augeas change ''' if os.path.isfile(filename) or filename == '/': if filename == '/': filename = None return filename else: return _workout_filename(os.path.dirname(filename))
python
def find_types_that_changed_kind( old_schema: GraphQLSchema, new_schema: GraphQLSchema ) -> List[BreakingChange]: """Find types that changed kind Given two schemas, returns a list containing descriptions of any breaking changes in the newSchema related to changing the type of a type. """ old_ty...
python
def _add_conflicting_arguments(self): """It's too dangerous to use `-y` and `-r` together.""" group = self._parser.add_mutually_exclusive_group() group.add_argument( '-y', '--yes', '--yeah', action='store_true', help='execute fixed command without confirmation...
python
def add(self, item): "Add an item (string) to the filter. Cannot be removed later!" for pos in self._hashes(item): self.hash |= (2 ** pos)
java
private void addWhere4ListPrint(final ListPrint _print) { final SQLSelectPart currentPart = sqlSelect.getCurrentPart(); if (currentPart == null) { sqlSelect.addPart(SQLPart.WHERE); } else { sqlSelect.addPart(SQLPart.AND); } sqlSelect.addColumnPart(0, "...
java
public Paths getPaths(ObjectNode obj, String location, ParseResult result) { final Paths paths = new PathsImpl(); if (obj == null) { return null; } Set<String> pathKeys = getKeys(obj); for (String pathName : pathKeys) { JsonNode pathValue = obj.get(pathNam...
python
def create_grid(self, grid_width, grid_height): """Create a grid layout with stacked widgets. Parameters ---------- grid_width : int the width of the grid grid_height : int the height of the grid """ self.grid_layout = QGridLayout() ...
java
public Set<IntIntEntry> entrySet () { return new AbstractSet<IntIntEntry>() { @Override public int size () { return _size; } @Override public Iterator<IntIntEntry> iterator() { return new IntEntryIterator(); } }; }
python
def format_params_diff(parameter_diff): """Handles the formatting of differences in parameters. Args: parameter_diff (list): A list of DictValues detailing the differences between two dicts returned by :func:`stacker.actions.diff.diff_dictionaries` Returns: string: A...
java
public RemoteUpdateResult updateMany(final Bson filter, final Bson update) { return proxy.updateMany(filter, update); }
python
def get_auto_correlation_time(chain, max_lag=None): r"""Compute the auto correlation time up to the given lag for the given chain (1d vector). This will halt when the maximum lag :math:`m` is reached or when the sum of two consecutive lags for any odd lag is lower or equal to zero. The auto correlatio...
python
def hook(self, function, dependencies=None): """Tries to load a hook Args: function (func): Function that will be called when the event is called Kwargs: dependencies (str): String or Iterable with modules whose hooks should be called before this one Raises: ...
python
def normalize_attr_strings(a: np.ndarray) -> np.ndarray: """ Take an np.ndarray of all kinds of string-like elements, and return an array of ascii (np.string_) objects """ if np.issubdtype(a.dtype, np.object_): # if np.all([type(x) is str for x in a]) or np.all([type(x) is np.str_ for x in a]) or np.all([type(x) ...
java
public static MultiLanguageText buildMultiLanguageText(final Locale locale, final String multiLanguageText) { return addMultiLanguageText(MultiLanguageText.newBuilder(), locale.getLanguage(), multiLanguageText).build(); }
java
public User loadUser (String authcode) throws PersistenceException { User user = (authcode == null) ? null : _repository.loadUserBySession(authcode); if (USERMGR_DEBUG) { log.info("Loaded user by authcode", "code", authcode, "user", user); } return user; }
java
public <F> F val(String propName) { Triple<String, Field, Reflecter<Object>> triple = getNestRefInfo(propName); return triple.getR().getPropVal(triple.getC(), triple.getL()); }
python
def validate_config_parameters(config_json, allowed_keys, allowed_types): """Validate parameters in config file.""" custom_fields = config_json.get(defs.PARAMETERS, []) for field in custom_fields: validate_field(field, allowed_keys, allowed_types) default = field.get(defs.DEFAULT) fi...
python
def close_stream(self): """ Closes the stream. Performs cleanup. """ self.keep_listening = False self.stream.stop_stream() self.stream.close() self.pa.terminate()
java
private void leftSearch( SearchComparator comp, GBSNode p, GBSNode r, Object searchKey, SearchNode point) { if (r == null) ...
java
public List<NodeData> getChildNodesData(NodeData parent) throws RepositoryException { long start = 0; if (LOG.isDebugEnabled()) { start = System.currentTimeMillis(); LOG.debug("getChildNodesData(" + parent.getQPath().getAsString() + ") >>>>>"); } try { ...
java
public IfcTextPath createIfcTextPathFromString(EDataType eDataType, String initialValue) { IfcTextPath result = IfcTextPath.get(initialValue); if (result == null) throw new IllegalArgumentException( "The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'"); return...
java
public void visit(NodeData node) throws RepositoryException { try { entering(node, currentLevel); if (maxLevel == INFINITE_DEPTH || currentLevel < maxLevel) { currentLevel++; visitChildProperties(node); visitChildNodes(node); cu...
java
private static void usage(PrintStream s) { s.println("usage: Client [options] <torrent>"); s.println(); s.println("Available options:"); s.println(" -h,--help Show this help and exit."); s.println(" -o,--output DIR Read/write data to directory DIR."); s.println(" -...
python
def normalize(a, axis=None): """Normalizes the input array so that it sums to 1. Parameters ---------- a : array Non-normalized input data. axis : int Dimension along which normalization is performed. Notes ----- Modifies the input **inplace**. """ a_sum = a.su...
python
def replace(self, messages, domain='messages'): """ Sets translations for a given domain. """ assert isinstance(messages, (dict, CaseInsensitiveDict)) assert isinstance(domain, (str, unicode)) self.messages[domain] = CaseInsensitiveDict({}) self.add(messages, dom...
python
def parsecounter(table, field, parsers=(('int', int), ('float', float))): """ Count the number of `str` or `unicode` values under the given fields that can be parsed as ints, floats or via custom parser functions. Return a pair of `Counter` objects, the first mapping parser names to the number of st...
java
public void delete(String vaultName, String resourceGroupName, String policyName) { deleteWithServiceResponseAsync(vaultName, resourceGroupName, policyName).toBlocking().single().body(); }
java
public InputStream decryptStream(InputStream input) throws SymmetricKeyException { try { EncryptedInputStream encryptedInputStream = new EncryptedInputStream(input); byte[] iv = encryptedInputStream.getIv(); Cipher cipher = getCipher(Cipher.DECRYPT_MODE, iv); retu...
java
protected byte[] compress(byte[] in) { if (in == null) { throw new NullPointerException("Can't compress null"); } ByteArrayOutputStream bos = new ByteArrayOutputStream(); GZIPOutputStream gz = null; try { gz = new GZIPOutputStream(bos); gz.write(in); } catch (IOException e) { ...
java
@Override public DeleteModelResult deleteModel(DeleteModelRequest request) { request = beforeClientExecution(request); return executeDeleteModel(request); }
java
@Override @Path("/{roleName}") @ApiOperation(value="Retrieve a role or all roles", notes="If roleName is not present, returns all roles.", response=Role.class, responseContainer="List") public JSONObject get(String path, Map<String,String> headers) throws ServiceException, JSONException { ...
java
public static TableColumnModel leftShift(TableColumnModel self, TableColumn column) { self.addColumn(column); return self; }
java
public static Set<Class<?>> findTypesAnnotatedWith(Class<? extends Annotation> annotation, Set<Class<?>> types) { if (annotation == null) { throw new IllegalArgumentException("An annotation type must be specified."); } return types.stream().filter(c -> c.isAnnotationPresent(annotati...
java
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); mWidth = measureWidth(widthMeasureSpec); mHeight = measureHeight(heightMeasureSpec); setMeasuredDimension(mWidth, mHeight); }
python
def send_http_request_with_query_parameters(context, method): """ Parameters: +-------------+--------------+ | param_name | param_value | +=============+==============+ | param1 | value1 | +-------------+--------------+ | param2 | value2 |...
java
protected final void addComponent(String name, String componentType, String rendererType) { _factories.put(name, new ComponentHandlerFactory(componentType, rendererType)); }
java
public String getType(String uri, String localName) { return attributes.getType(getRealIndex(uri, localName)); }
java
public SIBusMessage receiveNoWait(final SITransaction tran) throws SISessionDroppedException, SIConnectionDroppedException, SISessionUnavailableException, SIConnectionUnavailableException, SIConnectionLostException, SILimitExceededException, SINotAuthorizedException, SIRe...
python
def run_job(self, job_id, array_id = None): """This function is called to run a job (e.g. in the grid) with the given id and the given array index if applicable.""" # set the job's status in the database try: # get the job from the database self.lock() jobs = self.get_jobs((job_id,)) ...
java
public Content simpleTagOutput(Element element, DocTree simpleTag, String header) { ContentBuilder result = new ContentBuilder(); result.addContent(HtmlTree.DT(HtmlTree.SPAN(HtmlStyle.simpleTagLabel, new RawHtml(header)))); CommentHelper ch = utils.getCommentHelper(element); List<? exten...
python
def addReadGroupSet(self, readGroupSet): """ Adds the specified readGroupSet to this dataset. """ id_ = readGroupSet.getId() self._readGroupSetIdMap[id_] = readGroupSet self._readGroupSetNameMap[readGroupSet.getLocalId()] = readGroupSet self._readGroupSetIds.appen...
java
protected void writeClassToDisk(File targetDir, ClassWriter classWriter, String className) throws IOException { if (targetDir != null) { String fileName = className.replace('.', '/') + ".class"; File targetFile = new File(targetDir, fileName); targetFile.getParentFile().mkdi...
java
@Override public void execute(IntuitMessage intuitMessage) throws FMSException { LOG.debug("Enter DeserializeInterceptor..."); Response response = null; ResponseElements responseElements = intuitMessage.getResponseElements(); // get the Header to check whether it has content-type. //Header contentTypeHeade...
java
private void handleContentLength(Event event) { if (event.getContent() == null) { return; } if (maxContentLength == -1 || event.getContent().length() <= maxContentLength) { return; } if (maxContentLength < CUT_START_TAG.length() + CUT_END_TAG.length()) {...
java
public static CommerceTierPriceEntry fetchByCompanyId_First( long companyId, OrderByComparator<CommerceTierPriceEntry> orderByComparator) { return getPersistence() .fetchByCompanyId_First(companyId, orderByComparator); }
java
public void delete() { try { getDFS().delete(this.path, true); } catch (IOException e) { e.printStackTrace(); MessageDialog.openWarning(null, "Delete file", "Unable to delete file \"" + this.path + "\"\n" + e); } }
java
protected SqlSelect createSourceSelectForUpdate(SqlUpdate call) { final SqlNodeList selectList = new SqlNodeList(SqlParserPos.ZERO); selectList.add(SqlIdentifier.star(SqlParserPos.ZERO)); int ordinal = 0; for (SqlNode exp : call.getSourceExpressionList()) { // Force unique aliases to avoid a duplicate for Y ...
java
@Override public java.util.concurrent.Future<ListOpenIDConnectProvidersResult> listOpenIDConnectProvidersAsync( com.amazonaws.handlers.AsyncHandler<ListOpenIDConnectProvidersRequest, ListOpenIDConnectProvidersResult> asyncHandler) { return listOpenIDConnectProvidersAsync(new ListOpenIDConnectPr...
python
def upload_numpy_to_s3_shards(num_shards, s3, bucket, key_prefix, array, labels=None): """Upload the training ``array`` and ``labels`` arrays to ``num_shards`` s3 objects, stored in "s3://``bucket``/``key_prefix``/".""" shards = _build_shards(num_shards, array) if labels is not None: label_shard...
java
private static Set<String> setFor( String... elements ) { Set<String> set = new HashSet<String>(elements.length); set.addAll(Arrays.asList(elements)); return set; }
java
@XmlElementDecl(namespace = "http://www.opengis.net/gml", name = "coordinateOperationID") public JAXBElement<IdentifierType> createCoordinateOperationID(IdentifierType value) { return new JAXBElement<IdentifierType>(_CoordinateOperationID_QNAME, IdentifierType.class, null, value); }
java
public com.google.api.ads.adwords.axis.v201809.cm.Image getImage() { return image; }
python
def _create_api_call(self, method, _url, kwargs): """ This will create an APICall object and return it :param method: str of the html method ['GET','POST','PUT','DELETE'] :param _url: str of the sub url of the api call (ex. g/device/list) :param kwargs: dict of additional ar...
python
def process_text(text, save_xml='cwms_output.xml'): """Processes text using the CWMS web service. Parameters ---------- text : str Text to process Returns ------- cp : indra.sources.cwms.CWMSProcessor A CWMSProcessor, which contains a list of INDRA statements in its ...
java
public Redemption redeemCoupon(final String couponCode, final Redemption redemption) { return doPOST(Coupon.COUPON_RESOURCE + "/" + couponCode + Redemption.REDEEM_RESOURCE, redemption, Redemption.class); }
java
synchronized void setChannelFactory(ChannelFactory factory) throws ChannelFactoryException { if (factory != null && cf != null) { throw new ChannelFactoryException("ChannelFactory already exists"); } this.cf = factory; }
python
def find(self, sought, view='lemma'): ''' Returns a word instance for the hit if the "sought" word is found in the sentence. Per default the "lemma" view of the words is compared. You can specify the desired view with the optional "view" option. ''' for word in self.wordl...
java
@Override public JobReport mergerReports(JobReport... jobReports) { List<Long> startTimes = new ArrayList<>(); List<Long> endTimes = new ArrayList<>(); List<String> jobNames = new ArrayList<>(); JobParameters parameters = new JobParameters(); JobMetrics metrics = new JobMet...
python
def get_blockdata(self, x, z): """ Return the decompressed binary data representing a chunk. May raise a RegionFileFormatError(). If decompression of the data succeeds, all available data is returned, even if it is shorter than what is specified in the header (e.g. in c...
python
def genmatrix(self, num_processes=1): """ Actually generate the matrix :param num_processes: If you want to use multiprocessing to split up the work and run ``combinfunc()`` in parallel, specify ``num_processes > 1`` and this number of workers will be spun up, ...
python
def observed_data_to_xarray(self): """Convert observed data to xarray.""" observed_data_raw = _read_data(self.observed_data) variables = self.observed_data_var if isinstance(variables, str): variables = [variables] observed_data = {} for key, vals in observed_...
java
private static String generateMissingAuthorizationMessage(MissingAuthorization exceptionInfo) { StringBuilder builder = new StringBuilder(); String permissionName = exceptionInfo.getViolatedPermissionName(); String resourceType = exceptionInfo.getResourceType(); String resourceId = exceptionInfo.getReso...
java
public synchronized final String getHost() { if (host == null) { if (getEndpointAddress() != null && !getEndpointAddress().isUnresolved()) { host = getEndpointAddress().getHostName(); } if (host == null && httpURI != null) { ...
python
def _disable_encryption(self): # () -> None """Enable encryption methods for ciphers that support them.""" self.encrypt = self._disabled_encrypt self.decrypt = self._disabled_decrypt
java
public static void validatePromotionSuccessful(HttpResponse response, boolean dryRun, boolean failFast, TaskListener listener) throws IOException { StatusLine status = response.getStatusLine(); String content; try { content = ExtractorUtils.entityToString(response.getEntity()); ...
java
public ItemState getItemState(String itemIdentifier, int state) { return index.get(new IDStateBasedKey(itemIdentifier, state)); }
java
public boolean resetMoveTarget(int idx) { if (idx < 0 || idx >= m_maxAgents) { return false; } CrowdAgent ag = m_agents[idx]; // Initialize request. ag.targetRef = 0; vSet(ag.targetPos, 0, 0, 0); vSet(ag.dvel, 0, 0, 0); ag.targetPathqRef = Pa...
python
def glymurrc_fname(): """Return the path to the configuration file. Search order: 1) current working directory 2) environ var XDG_CONFIG_HOME 3) $HOME/.config/glymur/glymurrc """ # Current directory. fname = os.path.join(os.getcwd(), 'glymurrc') if os.path.exists(fname)...
java
public ServiceFuture<VirtualMachineInner> beginCreateOrUpdateAsync(String resourceGroupName, String vmName, VirtualMachineInner parameters, final ServiceCallback<VirtualMachineInner> serviceCallback) { return ServiceFuture.fromResponse(beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, vmName, param...
java
public static void set(String name, TagList list, double value) { final MonitorConfig config = MonitorConfig.builder(name).withTags(list).build(); set(config, value); }
python
def count_genes(model): """Count the number of distinct genes in model reactions.""" genes = set() for reaction in model.reactions: if reaction.genes is None: continue if isinstance(reaction.genes, boolean.Expression): genes.update(v.symbol for v in reaction.genes.va...
java
public static Bitmap load(String path) { try { File fi = new File(path); if (fi.isDirectory() || !fi.exists()) { return null; } return load(new FileInputStream(path), -1, -1); } catch (Exception e) { Log.e(TAG, "", e); ...
java
public boolean addAll(int index, Collection<? extends E> c) { try { boolean modified = false; ListIterator<E> e1 = listIterator(index); Iterator<? extends E> e2 = c.iterator(); while (e2.hasNext()) { e1.add(e2.next()); modified = tr...
java
private String _write_single_line(String tag, String text) { assert tag.length() < HEADER_WIDTH; return StringManipulationHelper.padRight(tag, HEADER_WIDTH) + text.replace('\n', ' ') + lineSep; }
python
def combine_info(self, all_infos): """Combine metadata for multiple datasets. When loading data from multiple files it can be non-trivial to combine things like start_time, end_time, start_orbit, end_orbit, etc. By default this method will produce a dictionary containing all values ...
python
def __initialize(self, resp): """Initialize from the response""" raw_data = xmltodict.parse(resp.content) root_key = list(raw_data.keys())[0] self.raw_data = raw_data.get(root_key) self.__initializeFromRaw()
python
def get_request_filename(request): '''Figure out the filename for an HTTP download.''' # Check to see if a filename is specified in the HTTP headers. if 'Content-Disposition' in request.info(): disposition = request.info()['Content-Disposition'] pieces = re.split(r'\s*;\s*', disposition) ...
java
@Override public AppSession getSession(String sessionId, Class<? extends AppSession> aClass) { if (sessionId == null) { throw new IllegalArgumentException("SessionId must not be null"); } if (!this.iss.exists(sessionId)) { return null; } AppSession appSession = null; try {...
python
def ad_address(mode, hit_id): """Get the address of the ad on AWS. This is used at the end of the experiment to send participants back to AWS where they can complete and submit the HIT. """ if mode == "debug": address = '/complete' elif mode in ["sandbox", "live"]: username = os...
python
def create_degrees(input_dim, hidden_dims, input_order='left-to-right', hidden_order='left-to-right'): """Returns a list of degree vectors, one for each input and hidden layer. A unit with degree d can only receive input from units with degree < d. Output ...
java
@Override public EClass getIfcBoilerType() { if (ifcBoilerTypeEClass == null) { ifcBoilerTypeEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI).getEClassifiers() .get(44); } return ifcBoilerTypeEClass; }
java
public void pushRoute(SipURI uri) { checkReadOnly(); javax.sip.address.SipURI sipUri = ((SipURIImpl) uri).getSipURI(); sipUri.setLrParam(); pushRoute(sipUri); }
python
def compute_cyclomatic_complexity(function): """ Compute the cyclomatic complexity of a function Args: function (core.declarations.function.Function) Returns: int """ # from https://en.wikipedia.org/wiki/Cyclomatic_complexity # M = E - N + 2P # where M is the complexity ...
java
@Override public Long sinterstore(final byte[] dstkey, final byte[]... keys) { checkIsInMultiOrPipeline(); client.sinterstore(dstkey, keys); return client.getIntegerReply(); }
java
public InputRegister getRegister(int index) { if (registers == null) { throw new IndexOutOfBoundsException("No registers defined!"); } if (index < 0) { throw new IndexOutOfBoundsException("Negative index: " + index); } if (index >= getWordCount()) { ...
python
def focusout(event): """Change style on focus out events.""" w = event.widget.spinbox bc = w.style.lookup("TEntry", "bordercolor", ("!focus",)) dc = w.style.lookup("TEntry", "darkcolor", ("!focus",)) lc = w.style.lookup("TEntry", "lightcolor", ("!focus",)) w.style.configu...
python
def add_signal_handlers(self): """Register handlers for UNIX signals (SIGHUP/SIGINT)""" try: self.loop.add_signal_handler(signal.SIGHUP, self.SIGHUP) except (RuntimeError, AttributeError): # pragma: no cover # windows pass try: self.loop.a...
java
public static boolean isSameDomain(String currentUrl, URI url) { String current = URI.create(getBaseUrl(currentUrl)).getHost() .toLowerCase(); String original = url.getHost().toLowerCase(); return current.endsWith(original); }
python
def _split_list(cls, items, separator=",", last_separator=" and "): """ Splits a string listing elements into an actual list. Parameters ---------- items: :class:`str` A string listing elements. separator: :class:`str` The separator between each i...
python
async def _wait_for_cmd(self, cmd, value, timeout=OTGW_DEFAULT_TIMEOUT): """ Wrap @cmd in applicable asyncio call. This method is a coroutine. """ if not self._connected: return try: return await asyncio.wait_for(self._protocol.issue_cmd(cmd, valu...
java
public Traverson followLink(final String rel, final Predicate<Link> predicate, final Map<String, Object> vars) { checkState(); hops.add(new Hop(rel, predicate, vars, true)); return this; }
java
public boolean setFirstChild(N newChild) { final N oldChild = this.nNorthWest; if (oldChild == newChild) { return false; } if (oldChild != null) { oldChild.setParentNodeReference(null, true); --this.notNullChildCount; firePropertyChildRemoved(0, oldChild); } if (newChild != null) { final N ...
java
public static final PatchOperationTarget createLocal(final File jbossHome, List<File> moduleRoots, List<File> bundlesRoots) throws IOException { final PatchTool tool = PatchTool.Factory.createLocalTool(jbossHome, moduleRoots, bundlesRoots); return new LocalPatchOperationTarget(tool); }
python
def init(deb1, deb2=False): """Initialize DEBUG and DEBUGALL. Allows other modules to set DEBUG and DEBUGALL, so their call to dprint or dprintx generate output. Args: deb1 (bool): value of DEBUG to set deb2 (bool): optional - value of DEBUGALL to set, defaults to ...
python
def settings_view_for_block(block_wrapper, settings_view_factory): """ Returns the settings view for an arbitrary block. Args: block_wrapper (BlockWrapper): The block for which a settings view is to be returned settings_view_factory (SettingsViewFactory):...
java
public boolean is(String... names) { boolean b = true; for (String n : names) { b &= name.toLowerCase().contains(n.toLowerCase()); } return b; }
java
private final void error() throws ParserException { Integer currentState = stateStack.peek(); parserErrors.addError(currentState); if (backtrackEnabled && !backtrackStack.isEmpty()) { trackBack(); return; } if (!backtrackEnabled) { logger.trace("No valid action available and back tracking is disable...
python
def get(self): """Return the number of seconds elapsed since object creation, or since last call to this function, whichever is more recent.""" elapsed = datetime.now() - self._previous self._previous += elapsed return elapsed.total_seconds()
java
@Override public EClass getIfcPositiveInteger() { if (ifcPositiveIntegerEClass == null) { ifcPositiveIntegerEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(900); } return ifcPositiveIntegerEClass; }