language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def merge_all_edges_between_two_vertices(self, vertex1, vertex2): """ Merges all edge between two supplied vertices into a single edge from a perspective of multi-color merging. Proxies a call to :meth:`BreakpointGraph._BreakpointGraph__merge_all_bgedges_between_two_vertices` :param vertex1: ...
python
def satoshi_to_currency(num, currency): """Converts a given number of satoshi to another currency as a formatted string rounded down to the proper number of decimal places. :param num: The number of satoshi. :type num: ``int`` :param currency: One of the :ref:`supported currencies`. :type curre...
python
def untrace_property(cls, accessor): """ Untraces given class property. :param cls: Class of the property. :type cls: object :param accessor: Property to untrace. :type accessor: property :return: Definition success. :rtype: bool """ if not is_traced(accessor.fget) or not is_tr...
java
public ValueList appendStringSet(String ...val) { super.append(new LinkedHashSet<String>(Arrays.asList(val))); return this; }
python
def _get_response_ms(self): """ Get the duration of the request response cycle is milliseconds. In case of negative duration 0 is returned. """ response_timedelta = now() - self.log['requested_at'] response_ms = int(response_timedelta.total_seconds() * 1000) retur...
python
def QueueQueryTasks(self, queue, limit=1): """Retrieves tasks from a queue without leasing them. This is good for a read only snapshot of the tasks. Args: queue: The task queue that this task belongs to, usually client.Queue() where client is the ClientURN object you want to schedule msgs on...
python
def _tfidf(x, reduced_term_freq, vocab_size, corpus_size): """Maps the terms in x to their (1/doc_length) * inverse document frequency. Args: x: A `Column` representing int64 values (most likely that are the result of calling string_to_int on a tokenized string). reduced_term_freq: A dense tensor of...
java
public static CommercePriceList fetchByCompanyId_Last(long companyId, OrderByComparator<CommercePriceList> orderByComparator) { return getPersistence() .fetchByCompanyId_Last(companyId, orderByComparator); }
python
def _get_public_room(self, room_name, invitees: List[User]): """ Obtain a public, canonically named (if possible) room and invite peers """ room_name_full = f'#{room_name}:{self._server_name}' invitees_uids = [user.user_id for user in invitees] for _ in range(JOIN_RETRIES): ...
python
def wait(hotkey=None, suppress=False, trigger_on_release=False): """ Blocks the program execution until the given hotkey is pressed or, if given no parameters, blocks forever. """ if hotkey: lock = _Event() remove = add_hotkey(hotkey, lambda: lock.set(), suppress=suppress, trigger_on...
python
def readiterinit(d): """ Prepare to read data with ms.iter* """ # set requested time range based on given parameters starttime_mjd = d['starttime_mjd'] timeskip = d['inttime']*d['nskip'] starttime = qa.getvalue(qa.convert(qa.time(qa.quantity(starttime_mjd+timeskip/(24.*60*60),'d'),form=['ymd'],...
python
def _run(self): """ This is the logic to run it all. Heavily influenced by this post: http://nickdesaulniers.github.io/blog/2015/05/25/interpreter-compiler-jit/ :return: """ i = 0 try: while i < len(self.program): if self.program[i] == ...
java
@Override public void close() throws IOException { synchronized (lock) { decoder = null; if (in != null) { in.close(); in = null; } } }
java
public static RawFrame createPL132(byte[] data, int offset) throws KNXFormatException { if (data.length - offset == 2) return new PL132Ack(data, offset); return new PL132LData(data, offset); }
python
def splitPrefix(name): """ Split the name into a tuple (I{prefix}, I{name}). The first element in the tuple is I{None} when the name does't have a prefix. @param name: A node name containing an optional prefix. @type name: basestring @return: A tuple containing the (2) parts of I{name} @rty...
java
public NotificationChain basicSetDuration(Parameter newDuration, NotificationChain msgs) { Parameter oldDuration = duration; duration = newDuration; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, BpsimPackage.SCENARIO_PARAMETERS__DURATION, oldDurat...
java
@Override public final String printNtz(final String pNumber, final String pDigSep, final String pDigGrSep, final Integer pDigitsInGroup) { if (pNumber == null || "".equals(pNumber)) { return ""; } int dotIdx = pNumber.indexOf("."); String leftWing; String rightWing; if (dotIdx == -1)...
java
public boolean insertBefore(final Node newNode, final Node oldNode) { if (oldNode == null || newNode == null) { return false; } int index = nodes.indexOf(oldNode); if (index != -1) { // Remove the parent from the new node if one exists if (newNode.get...
python
def from_json(cls, json_doc): """Parse a JSON string and build an entity.""" try: d = json.load(json_doc) except AttributeError: # catch the read() error d = json.loads(json_doc) return cls.from_dict(d)
java
public Request<UserBlocks> get(String userId) { Asserts.assertNotNull(userId, "user id"); String url = baseUrl .newBuilder() .addPathSegments("api/v2/user-blocks") .addPathSegment(userId) .build() .toString(); Custo...
python
def get_all_derivatives(self, address): """Get all targets derived directly or indirectly from the specified target. Note that the specified target itself is not returned. :API: public """ ret = [] direct = self.get_direct_derivatives(address) ret.extend(direct) for t in direct: ...
python
def to_table_data(self): """ :raises ValueError: :raises pytablereader.error.ValidationError: """ self._validate_source_data() for table_key, json_records in six.iteritems(self._buffer): headers = sorted(six.viewkeys(json_records)) self._loader....
java
public HllUpdate addAllBinary(Collection<BinaryValue> elements) { if (elements == null) { throw new IllegalArgumentException("Elements cannot be null"); } for (BinaryValue element : elements) { this.adds.add(element); } return this; ...
python
def corr(dataset, column, method="pearson"): """ Compute the correlation matrix with specified method using dataset. :param dataset: A Dataset or a DataFrame. :param column: The name of the column of vectors for which the correlation coefficient needs to be...
java
public static String readString(ChannelBuffer buffer, int length) { return readString(buffer, length, CharsetUtil.UTF_8); // char[] chars = new char[length]; // for (int i = 0; i < length; i++) // { // chars[i] = buffer.readChar(); // } // return new String(chars); }
python
def add_srec(self, records, overwrite=False): """Add given Motorola S-Records string. Set `overwrite` to ``True`` to allow already added data to be overwritten. """ for record in StringIO(records): type_, address, size, data = unpack_srec(record.strip()) if typ...
java
private void addFirstOfType() { for (Node node : nodes) { Index index = helper.getIndexInParent(node, true); if (index.index == 0) result.add(node); } }
java
public boolean isTrue(Configuration configuration) { for (int i = 0; i < this.variables.size(); ++i) { Variable variable = this.variables.get(i); if (configuration.valueAt(variable.getIndex()) == 1 && !this.negatedFlags.get(i)) return true; if (configuration.v...
java
public Collection<Tenant> getTenants() { checkServiceState(); Map<String, TenantDefinition> tenantMap = getAllTenantDefs(); List<Tenant> result = new ArrayList<>(); for (String tenantName : tenantMap.keySet()) { result.add(new Tenant(tenantMap.get(tenantName))); } ...
java
public List<String> getFiles(GerritQueryHandler gerritQueryHandler) { if (files == null) { files = FileHelper.getFilesByChange(gerritQueryHandler, id); } return files; }
java
public void savePCAToFile(String PCAFileName) throws Exception { if (isPcaInitialized) { throw new Exception("Cannot save, PCA is initialized!"); } if (V_t == null) { throw new Exception("Cannot save to file, PCA matrix is null!"); } BufferedWriter out = new BufferedWriter(new FileWriter(PCAFileN...
python
def _children(self): """Yield all direct children of this object.""" for codeobj in self.parameters: yield codeobj for codeobj in self.body._children(): yield codeobj
python
def _use_inf_as_na(key): """Option change callback for na/inf behaviour Choose which replacement for numpy.isnan / -numpy.isfinite is used. Parameters ---------- flag: bool True means treat None, NaN, INF, -INF as null (old way), False means None and NaN are null, but INF, -INF are ...
java
public void zone_zoneName_redirection_id_PUT(String zoneName, Long id, OvhRedirection body) throws IOException { String qPath = "/domain/zone/{zoneName}/redirection/{id}"; StringBuilder sb = path(qPath, zoneName, id); exec(qPath, "PUT", sb.toString(), body); }
java
public static Complex_F64[] findRoots(double... coefficients) { int N = coefficients.length-1; // Construct the companion matrix DMatrixRMaj c = new DMatrixRMaj(N,N); double a = coefficients[N]; for( int i = 0; i < N; i++ ) { c.set(i,N-1,-coefficients[i]/a); ...
python
def upload_tree(self, src, dst, ignore=None): """Recursively upload a directory tree. Although similar to shutil.copytree we don't follow symlinks. """ names = os.listdir(src) if ignore is not None: ignored_names = ignore(src, names) else: ignored...
java
public static File findInstanceResourcesDirectory( File applicationFilesDirectory, Component component ) { File root = new File( applicationFilesDirectory, Constants.PROJECT_DIR_GRAPH ); File result = new File( "No recipe directory." ); Set<Component> alreadyChecked = new HashSet<> (); for( Component c = compo...
java
public void addCache(String cacheName, AsyncLoadingCache cache) { children.put(cacheName, cache.synchronous()); }
java
public static base_responses update(nitro_service client, nsacl resources[]) throws Exception { base_responses result = null; if (resources != null && resources.length > 0) { nsacl updateresources[] = new nsacl[resources.length]; for (int i=0;i<resources.length;i++){ updateresources[i] = new nsacl(); ...
java
private void launchWithConfigurationString( final String evaluatorConfiguration, final String contextConfiguration, final Optional<String> serviceConfiguration, final Optional<String> taskConfiguration) { try (final LoggingScope lb = loggingScopeFactory.evaluatorLaunch(this.getId())) { ...
python
def _process_transfer(self, ud, ase, offsets, data): # type: (Uploader, blobxfer.models.upload.Descriptor, # blobxfer.models.azure.StorageEntity, # blobxfer.models.upload.Offsets, bytes) -> None """Process transfer instructions :param Uploader self: this :pa...
java
public CollectionInfo getCollectionInfo(int collectionId, String language) throws MovieDbException { TmdbParameters parameters = new TmdbParameters(); parameters.add(Param.ID, collectionId); parameters.add(Param.LANGUAGE, language); URL url = new ApiUrl(apiKey, MethodBase.COLLECTION).bu...
python
def unlock(self, passphrase, encrypted_seed=None): """Unlock the Wallet by decrypting the primary_private_seed with the supplied passphrase. Once unlocked, the private seed is accessible in memory and calls to `account.pay` will succeed. This is a necessary step for creating transactions...
java
public static String cleanSubOptions(String optionPrefix, Set<String> allowedSubOptions, String s) { StringBuilder sb = new StringBuilder(); if (!s.startsWith(optionPrefix)) return ""; StringTokenizer st = new StringTokenizer(s.substring(optionPrefix.length()), ","); while (st.hasMoreTok...
java
protected final <T extends ChronoEntity<T>> UnitRule<T> derive(T entity) { return this.derive(entity.getChronology()); }
python
def value_from_datadict(self, data, files, name): """Ensure the payload is a list of values. In the case of a sub form, we need to ensure the data is returned as a list and not a dictionary. When a dict is found in the given data, we need to ensure the data is converted to a lis...
python
def register_suffixes (suffixes, type): """ Specifies that targets with suffix from 'suffixes' have the type 'type'. If a different type is already specified for any of syffixes, issues an error. """ assert is_iterable_typed(suffixes, basestring) assert isinstance(type, basestring) for s in ...
java
public Paint getTopShadowGradient(Shape s) { Rectangle2D bounds = s.getBounds2D(); float minY = (float) bounds.getMinY(); float maxY = (float) bounds.getMaxY(); float midX = (float) bounds.getCenterX(); return new LinearGradientPaint(midX, minY, midX, max...
python
def resize(self, size, interp='nearest'): """Resize the image. Parameters ---------- size : int, float, or tuple * int - Percentage of current size. * float - Fraction of current size. * tuple - Size of the output image. interp : :obj:`str`...
python
def get_ed25519ll(): """Lazy import-and-test of ed25519 module""" global ed25519ll if not ed25519ll: try: import ed25519ll # fast (thousands / s) except (ImportError, OSError): # pragma nocover from . import ed25519py as ed25519ll # pure Python (hundreds / s) ...
python
def bencode(canonical): ''' Turns a dictionary into a bencoded str with alphabetized keys e.g., {'spam': 'eggs', 'cow': 'moo'} --> d3:cow3:moo4:spam4:eggse ''' in_dict = dict(canonical) def encode_str(in_str): out_str = str(len(in_str)) + ':' + in_str return out_str ...
java
@Override public CPDefinitionInventory findByCPDefinitionId(long CPDefinitionId) throws NoSuchCPDefinitionInventoryException { CPDefinitionInventory cpDefinitionInventory = fetchByCPDefinitionId(CPDefinitionId); if (cpDefinitionInventory == null) { StringBundler msg = new StringBundler(4); msg.append(_NO...
java
private GrammarInfo [] scanForGrammars () throws MojoExecutionException { if (!getSourceDirectory ().isDirectory ()) { return null; } GrammarInfo [] grammarInfos; getLog ().debug ("Scanning for grammars: " + getSourceDirectory ()); try { final GrammarDirectoryScanner scanner ...
python
def setParams(self, minSupport=0.3, minConfidence=0.8, itemsCol="items", predictionCol="prediction", numPartitions=None): """ setParams(self, minSupport=0.3, minConfidence=0.8, itemsCol="items", \ predictionCol="prediction", numPartitions=None) """ kwa...
python
def url_to_path(self, url): """Convert schema URL to path. :param url: The schema URL. :returns: The schema path or ``None`` if the schema can't be resolved. """ parts = urlsplit(url) try: loader, args = self.url_map.bind(parts.netloc).match(parts.path) ...
java
private void deleteStaleBackups() throws Exception { UfsStatus[] statuses = mUfs.listStatus(mBackupDir); if (statuses.length <= mRetainedFiles) { return; } // Sort the backup files according to create time from oldest to newest TreeMap<Instant, String> timeToFile = new TreeMap<>((a, b) -> ( ...
python
def active_aliases(self): """Get a filtered list of aliases based on configuration. Returns aliases and their mappings that are defined in the `SEARCH_MAPPINGS` config variable. If the `SEARCH_MAPPINGS` is set to `None` (the default), all aliases are included. """ whitel...
java
private Animator preparePressedAnimation() { Animator animation = ObjectAnimator.ofFloat(drawable, CircularProgressDrawable.CIRCLE_SCALE_PROPERTY, drawable.getCircleScale(), 0.65f); animation.setDuration(120); return animation; }
python
def fit(self, X, y=None, **kwargs): """ Fits the estimator to discover the feature importances described by the data, then draws those importances as a bar plot. Parameters ---------- X : ndarray or DataFrame of shape n x m A matrix of n instances with m feat...
python
def delete_user(self, user_descriptor): """DeleteUser. [Preview API] Disables a user. :param str user_descriptor: The descriptor of the user to delete. """ route_values = {} if user_descriptor is not None: route_values['userDescriptor'] = self._serialize.url('...
java
@Override public GetPasswordDataResult getPasswordData(GetPasswordDataRequest request) { request = beforeClientExecution(request); return executeGetPasswordData(request); }
python
def stop(self): """ Stop services and requestors and then connection. :return: self """ LOGGER.debug("rabbitmq.Driver.stop") for requester in self.requester_registry: requester.stop() self.requester_registry.clear() for service in self.service...
java
public void marshall(FieldStats fieldStats, ProtocolMarshaller protocolMarshaller) { if (fieldStats == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(fieldStats.getMin(), MIN_BINDING); pr...
python
def attention_lm_moe_base_ae(): """Base model with attention expert.""" hparams = attention_lm_moe_base_long_seq() hparams.attention_type = AttentionType.LOCAL_EXPERTS hparams.learning_rate = 0.05 hparams.learning_rate_warmup_steps = 10000 # According to noam, ("n", "da") seems better for harder-to-learn m...
python
def cls_register(cls, frameset, new_class, init_args, name=None): """ Register a new FrameSet or FrameSet subclass as a member/attribute of a class. Returns the new FrameSet or FrameSet subclass. Arguments: frameset : An existing FrameSet, or an iterable of strings. ...
python
def update_md5(filenames): """Update our built-in md5 registry""" import re for name in filenames: base = os.path.basename(name) f = open(name,'rb') md5_data[base] = md5(f.read()).hexdigest() f.close() data = [" %r: %r,\n" % it for it in md5_data.items()] data.s...
java
public JodaBeanSer withShortTypes(boolean shortTypes) { return new JodaBeanSer(indent, newLine, converter, iteratorFactory, shortTypes, deserializers, includeDerived); }
java
public java.util.List<String> getSpotFleetRequestIds() { if (spotFleetRequestIds == null) { spotFleetRequestIds = new com.amazonaws.internal.SdkInternalList<String>(); } return spotFleetRequestIds; }
java
public final void mINSERT() throws RecognitionException { try { int _type = INSERT; int _channel = DEFAULT_TOKEN_CHANNEL; // hql.g:36:8: ( 'insert' ) // hql.g:36:10: 'insert' { match("insert"); if (state.failed) return; } state.type = _type; state.channel = _channel; } finally { //...
java
public double distanceFrom(LatLong end) { double dLat = (end.getLatitude() - getLatitude()) * Math.PI / 180; double dLon = (end.getLongitude() - getLongitude()) * Math.PI / 180; double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(getLatitude() * Math.PI / 180) ...
java
@ObjectiveCName("forwardContentContentWithPeer:withContent:") public void forwardContent(Peer peer, AbsContent content) { modules.getMessagesModule().forwardContent(peer, content); }
python
def _has_message(self): """ Whether or not we have messages available for processing. """ sep = protocol.MINIMAL_LINE_SEPARATOR.encode(self.encoding) return sep in self._receive_buffer
java
public void setGroupMembers(List<String> membershipInfo) { for (String line : membershipInfo) { String[] fields = line.split("\\|"); if (fields.length < 2) { continue; } Set<String> users = StringUtils.commaDelimitedListToSet(fields[1]); ...
python
def set_hostname(self, value=None, default=False, disable=False): """Configures the global system hostname setting EosVersion: 4.13.7M Args: value (str): The hostname value default (bool): Controls use of the default keyword disable (bool): Contr...
java
private List<Partition> createUserSpecifiedPartitions() { List<Partition> partitions = new ArrayList<>(); List<String> watermarkPoints = state.getPropAsList(USER_SPECIFIED_PARTITIONS); boolean isEarlyStopped = state.getPropAsBoolean(IS_EARLY_STOPPED); if (watermarkPoints == null || watermarkPoints.si...
python
def isIsosceles(self): ''' True iff two side lengths are equal, boolean. ''' return (self.a == self.b) or (self.a == self.c) or (self.b == self.c)
python
def check_overscan(xstart, xsize, total_prescan_pixels=24, total_science_pixels=4096): """Check image for bias columns. Parameters ---------- xstart : int Starting column of the readout in detector coordinates. xsize : int Number of columns in the readout. t...
java
static double rgba( double r, double g, double b, double a ) { return Double.longBitsToDouble( Math.round( a * 0xFFFF ) << 48 | (colorLargeDigit(r) << 32) | (colorLargeDigit(g) << 16) | colorLargeDigit(b) ); }
python
def role_show(endpoint_id, role_id): """ Executor for `globus endpoint role show` """ client = get_client() role = client.get_endpoint_role(endpoint_id, role_id) formatted_print( role, text_format=FORMAT_TEXT_RECORD, fields=( ("Principal Type", "principal_typ...
java
@Override public EClass getIfcHumidifier() { if (ifcHumidifierEClass == null) { ifcHumidifierEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI).getEClassifiers() .get(314); } return ifcHumidifierEClass; }
python
def rename_edges(self, old_node_name, new_node_name): """ Change references to a node in existing edges. Args: old_node_name (str): The old name for the node. new_node_name (str): The new name for the node. """ graph = self.graph for node, edges in graph....
python
def log(self, level, msg): """ Logs the inputed message with the given level. :param level | <int> | logging level value msg | <unicode> :return <bool> success """ if self.isDestroyed(): return ...
python
def is_merge_origin(self): """True if cell is top-left in merged cell range.""" if self.gridSpan > 1 and not self.vMerge: return True if self.rowSpan > 1 and not self.hMerge: return True return False
python
def columnType( self ): """ Returns the column type for this item based on the current column. :return <orb.ColumnType> """ schema = self.treeWidget().parent().schema() if ( not schema ): return 0 column = schema.column(self.text(...
python
def resolve_label(self, label): """ Resolves a label for this module only. If the label refers to another module, an exception is raised. @type label: str @param label: Label to resolve. @rtype: int @return: Memory address pointed to by the label. @ra...
java
private boolean matches7000( ApiDifference apiDiff ) { throwIfMissing( false, true, false, false ); return SelectorUtils.matchPath( method, removeVisibilityFromMethodSignature( apiDiff ) ); }
java
public String setStringValue(String value) throws ControlException { String v = null; if(type!=V4L4JConstants.CTRL_TYPE_STRING) throw new UnsupportedMethod("This control is not a string control"); if (value.length() > max) throw new ControlException("The new string value for this control exceeds the m...
java
public DTMIterator createDTMIterator(int node) { // DescendantIterator iter = new DescendantIterator(); DTMIterator iter = new org.apache.xpath.axes.OneStepIteratorForward(Axis.SELF); iter.setRoot(node, this); return iter; // return m_dtmManager.createDTMIterator(node); }
python
def smallest_flagged(heap, row): """Search the heap for the smallest element that is still flagged. Parameters ---------- heap: array of shape (3, n_samples, n_neighbors) The heaps to search row: int Which of the heaps to search Returns ------- index: int T...
java
public static void notPositive(Long value, String message) { if(!validation) return; notNull(value); notNull(message); if(value > 0) throw new ParameterException(ErrorCode.POSITIVE, message); }
java
public static void addRowTimes(Matrix matrix, long diag, long fromCol, long row, double factor) { long cols = matrix.getColumnCount(); for (long col = fromCol; col < cols; col++) { matrix.setAsDouble( matrix.getAsDouble(row, col) - factor * matrix.getAsDouble(diag, col), row, col); } }
python
def float(self, var, default=NOTSET): """ :rtype: float """ return self.get_value(var, cast=float, default=default)
java
@Override public Set<String> getResourceNames(String dirName) { Set<String> resourceNames = new TreeSet<>(); List<ResourceBrowser> list = new ArrayList<>(); list.addAll(resourceInfoProviders); for (ResourceBrowser rsBrowser : list) { if (generatorRegistry.isPathGenerated(dirName)) { if (rsBrowser insta...
java
public GetIdentityPoolRolesResult withRoles(java.util.Map<String, String> roles) { setRoles(roles); return this; }
python
def get_versions() -> FileVersionResult: """ Search specific project files and extract versions to check. :return: A FileVersionResult object for reporting. """ version_counter = Counter() versions_match = False version_str = None versions_discovered = OrderedDict() for version_ob...
java
public void stop() { if (LOG.isDebugEnabled()) { LOG.debug("Stopping client"); } if (!running.compareAndSet(true, false)) { return; } synchronized (connections) { // wake up all connections for (Connection conn : connections.values()) { conn.interrupt(); }...
java
public static String getRequestMethod(HttpServletRequest req) { String method; if (req.getMethod() != null) method = req.getMethod().toUpperCase(); else method = AuditEvent.TARGET_METHOD_GET; return method; }
java
private static InputStream openSystemFile(String filename) throws FileNotFoundException { try { return new FileInputStream(filename); } catch(FileNotFoundException e) { // try with classloader String resname = File.separatorChar != '/' ? filename.replace(File.separatorChar, '/') : filename...
java
public InterceptorConfigurationBuilder before(Class<? extends AsyncInterceptor> before) { attributes.attribute(BEFORE).set(before); return this; }
java
public IndexTerminal forProperty(String property) { IndexExpression ix = (IndexExpression) this.astNode; ix.setPropertyName(property); IndexTerminal ret = new IndexTerminal(ix); return ret; }