language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static File createTempFile(String prefix, String suffix, File dir, boolean isReCreat) throws IORuntimeException { int exceptionsCount = 0; while (true) { try { File file = File.createTempFile(prefix, suffix, dir).getCanonicalFile(); if (isReCreat) { file.delete(); file.createNewFi...
java
@Override public void onGestureBegin(TransformGestureDetector detector) { FLog.v(TAG, "onGestureBegin"); mPreviousTransform.set(mActiveTransform); onTransformBegin(); // We only received a touch down event so far, and so we don't know yet in which direction a // future move event will follow. Ther...
java
public void marshall(CreateRule createRule, ProtocolMarshaller protocolMarshaller) { if (createRule == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(createRule.getInterval(), INTERVAL_BINDING); ...
java
public LocalDateTime minusDays(long days) { return (days == Long.MIN_VALUE ? plusDays(Long.MAX_VALUE).plusDays(1) : plusDays(-days)); }
python
def candidate(cls): """The ``Candidate``.""" return relationship( "Candidate", backref=backref( camel_to_under(cls.__name__) + "s", cascade="all, delete-orphan", cascade_backrefs=False, ), cascade_backrefs=Fa...
python
def link_bytecode(cls, attr_dict: Dict[str, str]) -> Type["LinkableContract"]: """ Return a cloned contract factory with the deployment / runtime bytecode linked. :attr_dict: Dict[`ContractType`: `Address`] for all deployment and runtime link references. """ if not cls.unlinked_...
java
public void exportAndBind() throws RemoteException, AlreadyBoundException, InterruptedException { Registry registry = LocateRegistry .createRegistry(arguments.getRegistryPortNumber()); registry.rebind(RMI_BINDING_NAME, this); Thread.sleep(2000)...
python
def urls_old(self, protocol=Resource.Protocol.http): ''' Iterate through all resources registered with this router and create a list endpoint and a detail endpoint for each one. Uses the router name as prefix and endpoint name of the resource when registered, to assemble the url pattern....
java
public static <A extends Number & Comparable<?>> NumberExpression<Double> asin(Expression<A> num) { return Expressions.numberOperation(Double.class, Ops.MathOps.ASIN, num); }
java
public static ClassLoader getClassLoader(final Class<?> c) { if (System.getSecurityManager() == null) return c.getClassLoader(); return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() { public ClassLoader run() { return c.getClassLoader(); ...
python
def print_table(column_names: IterableOfStrings, rows: IterableOfTuples, column_alignments: Optional[IterableOfStrings] = None, primary_column_idx: int = 0, ) -> None: """ Prints a table of information to the console. Automatically determines if th...
java
public <R> Future<R> map(final Function<? super T, R> success, final Function<Throwable, R> failure) { return Future.of(future.thenApply(success) .exceptionally(failure)); }
java
public static final <VertexKey extends Comparable<VertexKey>, VertexValue, Message, EdgeValue> VertexCentricIteration<VertexKey, VertexValue, Message, EdgeValue> withValuedEdges( DataSet<Tuple3<VertexKey, VertexKey, EdgeValue>> edgesWithValue, VertexUpdateFunction<VertexKey, VertexValue, Message> uf, ...
python
def set_serializer(self, serializer_name, compression=None): """ Configure the serializer to use for communication with the server. The serializer specified must be valid and in the :py:data:`.g_serializer_drivers` map. :param str serializer_name: The name of the serializer to use. :param str compression: ...
python
def getXlogStatus(self): """Returns Transaction Logging or Recovery Status. @return: Dictionary of status items. """ inRecovery = None if self.checkVersion('9.0'): inRecovery = self._simpleQuery("SELECT pg_is_in_recovery();") cur = self._conn...
java
public List<JSTypeExpression> getImplementedInterfaces() { if (info == null || info.implementedInterfaces == null) { return ImmutableList.of(); } return Collections.unmodifiableList(info.implementedInterfaces); }
java
private List<List<String>> processAcceptLanguage(String acceptLanguage) { StringTokenizer languageTokenizer = new StringTokenizer(acceptLanguage, ","); TreeMap<Double, List<String>> map = new TreeMap<Double, List<String>>(Collections.reverseOrder()); List<String> list; while (languageTo...
python
def scale_means(self, hs_dims=None, prune=False): """Return list of column and row scaled means for this slice. If a row/col doesn't have numerical values, return None for the corresponding dimension. If a slice only has 1D, return only the column scaled mean (as numpy array). If both r...
java
private void checkBuffer() { // Doc count limit if (docBuffer.size() >= bufferDocLimit) { log.debug("=== Buffer check: Doc limit reached '{}'", docBuffer.size()); submitBuffer(false); return; } // Size limit if (bufferSize > bufferSizeLimit) { ...
java
public JsonObject putAndEncrypt(String name, List<?> value, String providerName) { addValueEncryptionInfo(name, providerName, true); return put(name, JsonArray.from(value)); }
python
def update_extent_from_rectangle(self): """Update extent value in GUI based from the QgsMapTool rectangle. .. note:: Delegates to update_extent() """ self.show() self.canvas.unsetMapTool(self.rectangle_map_tool) self.canvas.setMapTool(self.pan_tool) rectangle =...
python
def load_package(package_dir, package=None, exclude=None, default_section=_DEFAULT_SECTION): """ 从目录中载入配置文件 :param package_dir: :param package: :param exclude: :param default_section: :return: """ init_py = '__init__.py' py_ext = '.py' files = os.listdir(package_dir) if i...
python
def add_devs_custom_views(custom_view_name, dev_list, auth, url): """ function takes a list of devIDs from devices discovered in the HPE IMC platform and issues a RESTFUL call to add the list of devices to a specific custom views from HPE IMC. :param custom_view_name: str of the target custom view name...
python
def validate_regexp(ctx, param, value): """ Validate and compile regular expression. """ if value: try: value = re.compile(value) except ValueError: raise click.BadParameter('invalid regular expression.') return value
python
def parse(self): """ Reads all lines from the current data source and yields each FileResult objects """ if self.data is None: raise ValueError('No input data provided, unable to parse') for line in self.data: parts = line.strip().split() try...
python
def csv_to_transactions(handle, source_encoding="latin1", date_format="%d-%m-%Y", thousand_sep=".", decimal_sep=","): """ Parses CSV data from stream and returns ``Transactions``. Args: index: The index of this row in the original CSV file. Used for sorting `...
java
private void obtainStyledAttributes(@Nullable final AttributeSet attributeSet, @AttrRes final int defaultStyle, @StyleRes final int defaultStyleResource) { TypedArray typedArray = getContext() .obtainStyledAttributes...
java
public static synchronized <T> T mock(Class<T> type) { return DefaultMockCreator.mock(type, false, false, null, null, (Method[]) null); }
java
public static OutputStream quoteOutputStream(final OutputStream out ) throws IOException { return new OutputStream() { private byte[] data = new byte[1]; @Override public void write(byte[] data, int off, int len) throws IOException { quoteHtml...
java
public DescribeAgentVersionsResult withAgentVersions(AgentVersion... agentVersions) { if (this.agentVersions == null) { setAgentVersions(new com.amazonaws.internal.SdkInternalList<AgentVersion>(agentVersions.length)); } for (AgentVersion ele : agentVersions) { this.agentV...
java
public List<Discussion> getCommitDiscussions(Object projectIdOrPath, Integer commitId) throws GitLabApiException { Pager<Discussion> pager = getCommitDiscussionsPager(projectIdOrPath, commitId, getDefaultPerPage()); return (pager.all()); }
python
def chugid_and_umask(runas, umask, group=None): ''' Helper method for for subprocess.Popen to initialise uid/gid and umask for the new process. ''' set_runas = False set_grp = False current_user = getpass.getuser() if runas and runas != current_user: set_runas = True run...
java
public static Document create(@NonNull String text, @NonNull Map<AttributeType, ?> attributes) { return DocumentFactory.getInstance().create(text, Hermes.defaultLanguage(), attributes); }
python
def get_direct_message(self): """ :reference: https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-message :allowed_param:'id', 'full_text' """ return bind_api( api=self, path='/direct_messages/show/{id}.json', ...
java
public static <T> T[] removeEle(T[] array, T element) throws IllegalArgumentException { return remove(array, indexOf(array, element)); }
java
private File writeVersionInfoTemplateToTempFile() throws MojoExecutionException { try { final File versionInfoSrc = File.createTempFile( "msbuild-maven-plugin_" + MOJO_NAME, null ); InputStream is = getClass().getResourceAsStream( DEFAULT_VERSION_INFO_TEMPLATE ); ...
java
public static String getCurrentAbsolutPathWithoutDotAndSlash() { final File currentAbsolutPath = new File("."); return currentAbsolutPath.getAbsolutePath().substring(0, currentAbsolutPath.getAbsolutePath().length() - 2); }
python
def run(self, packets): """Run automatically. Positional arguments: * packets -- list<dict>, list of packet dicts to be reassembled """ for packet in packets: frag_check(packet, protocol=self.protocol) info = Info(packet) self.reassembly(...
python
def strip_context_items(self, a_string): """Strip PaloAlto-specific output. PaloAlto will also put a configuration context: [edit] This method removes those lines. """ strings_to_strip = [r"\[edit.*\]"] response_list = a_string.split(self.RESPONSE_RETURN) ...
java
@NonNull private List<String> mapObsoleteElements(List<String> names) { List<String> elementsToRemove = new ArrayList<>(names.size()); for (String name : names) { if (name.startsWith("android")) continue; elementsToRemove.add(name); } return elementsToRemove; ...
java
public static String preprocess(String text) { return text.replaceAll("\\p{P}", " ").replaceAll("\\s+", " ").toLowerCase(Locale.getDefault()); }
python
def get_handler(): """Return the handler as a named tuple. The named tuple attributes are 'host', 'port', 'signum'. Return None when no handler has been registered. """ host, port, signum = _pdbhandler._registered() if signum: return Handler(host if host else DFLT_ADDRESS[0].encode(), ...
python
def parse_file_type(file_type): ''' :param file_type: file type string 'description (*.file_extension1;*.file_extension2)' as required by file filter in create_file_dialog :return: (description, file extensions) tuple ''' valid_file_filter = r'^([\w ]+)\((\*(?:\.(?:\w+|\*))*(?:;\*\.\w+)*)\)$' ma...
python
def reindex(self, indexers=None, method=None, tolerance=None, copy=True, **indexers_kwargs): """Conform this object onto a new set of indexes, filling in missing values with NaN. Parameters ---------- indexers : dict. optional Dictionary with keys giv...
python
def ctype(self): """Returns the name of the c_type from iso_c_binding to use when declaring the output parameter for interaction with python ctypes. """ if self.dtype == "logical": return "C_BOOL" elif self.dtype == "complex": #We don't actually know what ...
java
protected void skipPad() throws IOException { if (bytesRead > 0) { int extra = (int) (bytesRead % TarConstants.DATA_BLOCK); if (extra > 0) { long bs = 0; while (bs < TarConstants.DATA_BLOCK - extra) { long res = skip(TarConstants.DATA_BLOCK - extra - bs); bs += res; } } } ...
python
def dump(self): """ Dump the database using the postgres custom format """ dumpfile = self.args.dumpfile if not dumpfile: db, env = self.get_db_args_env() dumpfile = fileutils.timestamp_filename( 'omero-database-%s' % db['name'], 'pgdump') ...
java
public int getBlastWordSize() { if (param.containsKey(WORD_SIZE)) { return Integer.parseInt(getAlignmentOption(WORD_SIZE)); } // return default word size value try { BlastProgramEnum programType = getBlastProgram(); switch (programType) { case blastn: return 11; case megablast: return 28...
python
def make_element(builder, tag, content): """Make an element with this tag and text content""" builder.start(tag, {}) builder.data(content) # Must be UTF-8 encoded builder.end(tag)
java
public ProxySettings setServer(URL url) { if (url == null) { return this; } try { return setServer(url.toURI()); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } }
java
@Override public void eUnset(int featureID) { switch (featureID) { case AfplibPackage.MMORG__OV_LID: setOVLid(OV_LID_EDEFAULT); return; case AfplibPackage.MMORG__FLAGS: setFlags(FLAGS_EDEFAULT); return; case AfplibPackage.MMORG__OV_LNAME: setOVLname(OV_LNAME_EDEFAULT); return; } ...
java
public synchronized void addProjection( String externalNodeKey, String projectedNodeKey, String alias, SessionCache systemSession) { Projection projection = new Projection(external...
python
def list_by_group(self, id_ugroup): """Search Administrative Permission by Group User by identifier. :param id_ugroup: Identifier of the Group User. Integer value and greater than zero. :return: Dictionary with the following structure: :: {'perms': [{'ugrupo': < ugrupo_id...
python
def t_quotedvar_DOLLAR_OPEN_CURLY_BRACES(t): r'\$\{' if re.match(r'[A-Za-z_]', peek(t.lexer)): t.lexer.begin('varname') else: t.lexer.begin('php') return t
python
def chmod_r(root: str, permission: int) -> None: """ Recursive ``chmod``. Args: root: directory to walk down permission: e.g. ``e.g. stat.S_IWUSR`` """ os.chmod(root, permission) for dirpath, dirnames, filenames in os.walk(root): for d in dirnames: os.chmod(o...
java
public void fireIndexedPropertyChange(String propertyName, int index, Object oldValue, Object newValue) { if (oldValue == null || newValue == null || !oldValue.equals(newValue)) { firePropertyChange(new IndexedPropertyChangeEvent(source, propertyName, oldValue, newValue, index)); } }
python
def verify_jwt_in_request(): """ Ensure that the requester has a valid access token. This does not check the freshness of the access token. Raises an appropiate exception there is no token or if the token is invalid. """ if request.method not in config.exempt_methods: jwt_data = _decode_...
python
def add_note(self, content): """Add a note to the project. .. warning:: Requires Todoist premium. :param content: The note content. :type content: str >>> from pytodoist import todoist >>> user = todoist.login('john.doe@gmail.com', 'password') >>> project = use...
java
public static File[] toFiles(final URL[] urls) throws UncheckedIOException { if (N.isNullOrEmpty(urls)) { return new File[0]; } final File[] files = new File[urls.length]; for (int i = 0; i < urls.length; i++) { files[i] = toFile(urls[i]); } ...
python
def select_from_fv_by_seeds(fv, seeds, unique_cls): """ Tool to make simple feature functions take features from feature array by seeds. :param fv: ndarray with lineariezed feature. It's shape is MxN, where M is number of image pixels and N is number of features :param seeds: ndarray with seeds. Doe...
java
@Override public void returnConnection(Connection conn) { try { if (conn instanceof MyConnectionInvocationHandler) { DbcHelper.returnConnection(((MyConnectionInvocationHandler) conn).target); } else { DbcHelper.returnConnection(conn); } ...
java
@Override public List<CPDefinitionLink> findByCPD_T(long CPDefinitionId, String type, int start, int end, OrderByComparator<CPDefinitionLink> orderByComparator) { return findByCPD_T(CPDefinitionId, type, start, end, orderByComparator, true); }
python
def _assemble_regulate_activity(self, stmt): """Example: p(HGNC:MAP2K1) => act(p(HGNC:MAPK1))""" act_obj = deepcopy(stmt.obj) act_obj.activity = stmt._get_activity_condition() # We set is_active to True here since the polarity is encoded # in the edge (decreases/increases) ...
java
public void marshall(GetCoreDefinitionVersionRequest getCoreDefinitionVersionRequest, ProtocolMarshaller protocolMarshaller) { if (getCoreDefinitionVersionRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarsha...
java
public static TransactionException hasNotAllowed(Thing thing, Attribute attribute) { return create(HAS_INVALID.getMessage(thing.type().label(), attribute.type().label())); }
java
public void setResources(java.util.Collection<Resource> resources) { if (resources == null) { this.resources = null; return; } this.resources = new java.util.ArrayList<Resource>(resources); }
python
def evaluate_expression(dbg, frame, expression, is_exec): '''returns the result of the evaluated expression @param is_exec: determines if we should do an exec or an eval ''' if frame is None: return # Not using frame.f_globals because of https://sourceforge.net/tracker2/?func=detail&aid=254...
java
public PeriodDuration normalizedStandardDays() { long totalSecs = period.getDays() * SECONDS_PER_DAY + duration.getSeconds(); int splitDays = Math.toIntExact(totalSecs / SECONDS_PER_DAY); long splitSecs = totalSecs % SECONDS_PER_DAY; if (splitDays == period.getDays() && splitSecs == dura...
python
def create_config(kwargs=None, call=None): ''' Creates a Linode Configuration Profile. name The name of the VM to create the config for. linode_id The ID of the Linode to create the configuration for. root_disk_id The Root Disk ID to be used for this config. swap_disk...
python
def joinMeiUyir(mei_char, uyir_char): """ This function join mei character and uyir character, and retuns as compound uyirmei unicode character. Inputs: mei_char : It must be unicode tamil mei char. uyir_char : It must be unicode tamil uyir char. Written By : Arulalan.T Date : ...
python
def Dropout(x, params, rate=0.0, mode='train', rng=None, **kwargs): """Layer construction function for a dropout layer with given rate.""" del params, kwargs if rng is None: msg = ('Dropout layer requires apply_fun to be called with a rng keyword ' 'argument. That is, instead of `Dropout(params, in...
python
def to_er7(self, encoding_chars=None, trailing_children=False): """ Return the ER7-encoded string :type encoding_chars: ``dict`` :param encoding_chars: a dictionary containing the encoding chars or None to use the default (see :func:`get_default_encoding <hl7apy.get_default_...
python
def repo( state, host, name, baseurl, present=True, description=None, enabled=True, gpgcheck=True, gpgkey=None, ): ''' Add/remove/update yum repositories. + name: filename for the repo (in ``/etc/yum/repos.d/``) + baseurl: the baseurl of the repo + present: whether the ``.repo`` file should...
java
public void splitField(String sourceField, String targetField, String splitString, String index) { TransformationStep step = new TransformationStep(); step.setTargetField(targetField); step.setSourceFields(sourceField); step.setOperationParameter(TransformationConstants.SPLIT_PARAM, spli...
java
public static Resource getOrCreateChild(Resource resource, String relPath, String primaryTypes) throws RepositoryException { Resource child = null; if (resource != null) { ResourceResolver resolver = resource.getResourceResolver(); String path = resource.getPath(); ...
python
def set_artist(self, artist): """Sets song's artist :param artist: artist """ self._set_attr(TPE1(encoding=3, text=artist.decode('utf-8')))
python
def on_train_begin(self, **kwargs: Any) -> None: "Prepare MLflow experiment and log params" self.client = mlflow.tracking.MlflowClient(self.uri) exp = self.client.get_experiment_by_name(self.exp_name) self.exp_id = self.client.create_experiment(self.exp_name) if exp is None else exp.expe...
python
def matchTypes(accept_types, have_types): """Given the result of parsing an Accept: header, and the available MIME types, return the acceptable types with their quality markdowns. For example: >>> acceptable = parseAcceptHeader('text/html, text/plain; q=0.5') >>> matchTypes(acceptable, ['text/...
java
private ListenableFuture<ZkWorker> addWorker(final Worker worker) { log.info("Worker[%s] reportin' for duty!", worker.getHost()); try { cancelWorkerCleanup(worker.getHost()); final String workerStatusPath = JOINER.join(indexerZkConfig.getStatusPath(), worker.getHost()); final PathChildrenC...
java
public String getColumnClassName(int column) throws SQLException { checkColumn(column); Type type = resultMetaData.columnTypes[--column]; return type.getJDBCClassName(); }
java
public void resetColumnLabel(final String schema) { Map<String, Integer> labelAndIndexMap = new HashMap<>(1, 1); labelAndIndexMap.put(schema, 1); resetLabelAndIndexMap(labelAndIndexMap); }
java
public void set(Versioned<E> element) { if(element == null) throw new NullPointerException("cannot set a null element"); if(_lastCall != LastCall.NEXT && _lastCall != LastCall.PREVIOUS) throw new IllegalStateException("neither next() nor previous() has been called"); _st...
java
public Stats getCollectionStats(String collectionId, Date date) throws FlickrException { return getStats(METHOD_GET_COLLECTION_STATS, "collection_id", collectionId, date); }
python
def check(source, filename='<string>', report_level=docutils.utils.Reporter.INFO_LEVEL, ignore=None, debug=False): """Yield errors. Use lower report_level for noisier error output. Each yielded error is a tuple of the form: (line_number, message) Line ...
java
public static String encodeAsXMLName(String s) { StringBuilder sb = new StringBuilder("_"); for (byte b : s.getBytes(Charset.forName("UTF-8"))) { sb.append(Integer.toHexString((b >>> 4) & 0xF)); sb.append(Integer.toHexString(b & 0xF)); } return sb.toString(); }
java
public boolean isAnyPermissionPermanentlyDenied() { boolean hasPermanentlyDeniedAnyPermission = false; for (PermissionDeniedResponse deniedResponse : deniedPermissionResponses) { if (deniedResponse.isPermanentlyDenied()) { hasPermanentlyDeniedAnyPermission = true; break; } } ...
python
def create_index(self, columns=None, optlevel=None, kind=None): """ Create a pytables index on the specified columns note: cannot index Time64Col() or ComplexCol currently; PyTables must be >= 3.0 Parameters ---------- columns : False (don't create an index),...
java
public static String getNode(Long nodeId) { // 根据nodeId构造path return MessageFormat.format(ArbitrateConstants.NODE_NID_FORMAT, String.valueOf(nodeId)); }
python
def linguist_field_names(self): """ Returns linguist field names (example: "title" and "title_fr"). """ return list(self.model._linguist.fields) + list( utils.get_language_fields(self.model._linguist.fields) )
java
protected String handleAddException(IOException e, ItemData item) throws RepositoryException, InvalidItemStateException { StringBuilder message = new StringBuilder("["); message.append(containerName).append("] ADD ").append(item.isNode() ? "NODE. " : "PROPERTY. "); String errMessage = e.getM...
python
def getLinearityFunction(expTimes, imgs, mxIntensity=65535, min_ascent=0.001, ): ''' returns offset, ascent of image(expTime) = offset + ascent*expTime ''' # TODO: calculate [min_ascent] from noise function # instead of having it as variable ascent, offset...
java
public static String requireNotEmpty(final String str) throws NullPointerException, IllegalArgumentException { if (str.length() == 0) { throw new IllegalArgumentException(); } return str; }
java
@Override public byte[] readBuffer(final ChannelBuffer buffer) { int len = getLength(); byte[] matched = new byte[len]; buffer.readBytes(matched); return matched; }
python
def _cluster(bam_file, ma_file, out_dir, reference, annotation_file=None): """ Connect to seqcluster to run cluster with python directly """ seqcluster = op.join(get_bcbio_bin(), "seqcluster") # cl = ["cluster", "-o", out_dir, "-m", ma_file, "-a", bam_file, "-r", reference] if annotation_file: ...
python
def writeChunk(self, stream, filename, chunkIdx=None): """ Streams an uploaded chunk to a file. :param stream: the binary stream that contains the file. :param filename: the name of the file. :param chunkIdx: optional chunk index (for writing to a tmp dir) :return: no of...
python
def make_motif34lib(): ''' This function generates the motif34lib.mat library required for all other motif computations. Not to be called externally. ''' from scipy import io import os def motif3generate(): n = 0 M = np.zeros((54, 6), dtype=bool) # isomorphs # canon...
java
public void start(Xid xid, int flags) throws XAException { if (trace) log.tracef("start(%s, %s)", xid, flags); if (currentXid != null && flags == XAResource.TMNOFLAGS) { throw new LocalXAException(bundle.tryingStartNewTxWhenOldNotComplete( currentXid, xid, ...
java
public void continueIfExecutionDoesNotAffectNextOperation(Callback<PvmExecutionImpl, Void> dispatching, Callback<PvmExecutionImpl, Void> continuation, PvmExecutionImpl execution) { String lastAct...
python
def _getPublicSignupInfo(siteStore): """ Get information about public web-based signup mechanisms. @param siteStore: a store with some signups installed on it (as indicated by _SignupTracker instances). @return: a generator which yields 2-tuples of (prompt, url) where 'prompt' is unicode brief...
java
private boolean prepareListData() { Set<String> headers = new HashSet<>(); listDataHeader = new ArrayList<String>(); //category, content listDataChild = new HashMap<String, List<String>>(); if (sampleFactory==null || additionActivitybasedSamples==null) { //getActivit...