language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def _chooseBestSegmentPerColumn(cls, connections, matchingCells, allMatchingSegments, potentialOverlaps, cellsPerColumn): """ For all the columns covered by 'matchingCells', choose the column's matching segment with largest number of active...
java
public void nextStage(final String stageName) { assertNotNull("Cannot move to a null stage", stageName); execs.forEach(consumer(StageExec::preserve)); stage = stage.nextStage(stageName); prepare(); }
java
public static ECP weakBBSign(BIG sk, BIG m) { BIG exp = IdemixUtils.modAdd(sk, m, IdemixUtils.GROUP_ORDER); exp.invmodp(IdemixUtils.GROUP_ORDER); return IdemixUtils.genG1.mul(exp); }
python
def get_connection(self, internal=False): """Get a live connection to this instance. :param bool internal: Whether or not to use a DC internal network connection. :rtype: :py:class:`redis.client.StrictRedis` """ # Determine the connection string to use. connect_string =...
java
@Override public List<CommerceOrder> findByBillingAddressId(long billingAddressId, int start, int end, OrderByComparator<CommerceOrder> orderByComparator) { return findByBillingAddressId(billingAddressId, start, end, orderByComparator, true); }
java
private void setCollectionValue(Object entity, Object thriftColumnValue, Attribute attribute) { try { ByteBuffer valueByteBuffer = ByteBuffer.wrap((byte[]) thriftColumnValue); if (Collection.class.isAssignableFrom(((Field) attribute.getJavaMember()).getType())) { ...
python
def imsave(path, img, channel_first=False, as_uint16=False, auto_scale=True): """ Save image by cv2 module. Args: path (str): output filename img (numpy.ndarray): Image array to save. Image shape is considered as (height, width, channel) by default. channel_first: This ar...
python
def pad_timestamp(string, pad_str=PAD_6_UP): """ >>> pad_timestamp('20') '209912' >>> pad_timestamp('2014') '201412' >>> pad_timestamp('20141011') '20141011' >>> pad_timestamp('201410110010') '201410110010' """ str_len = len(string) pad_len = len(pad_str) if str...
python
def get_initial(self, form, name): """ Get the initial data that got passed into the superform for this composite field. It should return ``None`` if no initial values where given. """ if hasattr(form, 'initial'): return form.initial.get(name, None) r...
python
def read_df_or_series_from_csv(desired_type: Type[pd.DataFrame], file_path: str, encoding: str, logger: Logger, **kwargs) -> pd.DataFrame: """ Helper method to read a dataframe from a csv file. By default this is well suited for a dataframe with headers in the first row, for e...
python
def absolute_magnitude(self, richness=1, steps=1e4): """ Calculate the absolute visual magnitude (Mv) from the richness by transforming the isochrone in the SDSS system and using the g,r -> V transform equations from Jester 2005 [astro-ph/0506022]. Parameters: -...
java
public static <T> List<Optional<LocalProperty<T>>> normalize(List<? extends LocalProperty<T>> localProperties) { List<Optional<LocalProperty<T>>> normalizedProperties = new ArrayList<>(localProperties.size()); Set<T> constants = new HashSet<>(); for (LocalProperty<T> localProperty : localPro...
java
public static Status cpeUri(String value) { try { String[] parts = value.split(":"); if (parts.length > 8 || parts.length == 1 || !"cpe".equalsIgnoreCase(parts[0])) { LOG.warn("The CPE (" + value + ") is invalid as it is not in the CPE 2.2 URI format"); re...
java
public static @CheckForNull Queue.Item scheduleBuild2(final Job<?,?> job, int quietPeriod, Action... actions) { if (!(job instanceof ParameterizedJob)) { return null; } return new ParameterizedJobMixIn() { @Override protected Job asJob() { return job; ...
java
@Override public java.util.List<com.liferay.commerce.product.model.CPDefinitionOptionValueRel> getCPDefinitionOptionValueRelsByUuidAndCompanyId( String uuid, long companyId) { return _cpDefinitionOptionValueRelLocalService.getCPDefinitionOptionValueRelsByUuidAndCompanyId(uuid, companyId); }
java
public static CommerceOrder fetchByUserId_First(long userId, OrderByComparator<CommerceOrder> orderByComparator) { return getPersistence().fetchByUserId_First(userId, orderByComparator); }
java
public static List<PointIndex_I32> fitPolygon(List<Point2D_I32> sequence, boolean loop, int minimumSideLength , double cornerPenalty ) { PolylineSplitMerge alg = new PolylineSplitMerge(); alg.setLoops(loop); alg.setMinimumSideLength(minimumSideLength); alg.setCornerScorePenalty(cornerPenalty); ...
java
public static void assertNotEquals(String message, String expectedStr, String actualStr, JSONComparator comparator) throws JSONException { JSONCompareResult result = JSONCompare.compareJSON(expectedStr, actualStr, comparator); if (result.passed()) { throw new AssertionError(getCombin...
java
public void put(final byte[] data, final String key, final String token, final UpCompletionHandler complete, final UploadOptions options) { final UpToken decodedToken = UpToken.parse(token); if (areInvalidArg(key, data, null, token, decodedToken, complete)) { return; ...
python
def tab_join(ToMerge, keycols=None, nullvals=None, renamer=None, returnrenaming=False, Names=None): ''' Database-join for tabular arrays. Wrapper for :func:`tabular.spreadsheet.join` that deals with the coloring and returns the result as a tabarray. Method calls:: data ...
python
def select_uuid_like_indexes_on_table(model, cursor): """ Gets a list of database index names for the given model for the uuid-containing fields that have had a like-index created on them. :param model: Django model :param cursor: database connection cursor :return: list of database rows; the f...
python
def save(self, *args, **kwargs): """ Set the description field on save. """ if self.gen_description: self.description = strip_tags(self.description_from_content()) super(MetaData, self).save(*args, **kwargs)
python
def lock_holders(path, zk_hosts=None, identifier=None, max_concurrency=1, timeout=None, ephemeral_lease=False, profile=None, scheme=None, username=None, password=None,...
python
def delete(self, key=None): """Deletes the given key, or the whole bucket.""" # Delete the whole bucket. if key is None: # Delete everything in the bucket. for key in self.all(): key.delete() # Delete the bucket. return self._boto...
python
def exec_resize(self, exec_id, height=None, width=None): """ Resize the tty session used by the specified exec command. Args: exec_id (str): ID of the exec instance height (int): Height of tty session width (int): Width of tty session """ if ...
python
def require_meta_and_content(self, content_handler, params, **kwargs): """Require 'meta' and 'content' dictionaries using proper hander. Args: content_handler (callable): function that accepts ``params, meta, **kwargs`` argument and returns dictionary for ``c...
java
private boolean checkConstraint(Collection<String> constraints, Tile tile) { return tile != null && constraints.contains(mapGroup.getGroup(tile)) && !tile.getFeature(TileCollision.class).getCollisionFormulas().isEmpty(); }
python
def allow_unregister(self, plugin_override=True): """ Returns True if students can unregister from course """ vals = self._hook_manager.call_hook('course_allow_unregister', course=self, default=self._allow_unregister) return vals[0] if len(vals) and plugin_override else self._allow_unregister
java
public final Ix<T> switchIfEmpty(Iterable<? extends T> other) { return new IxSwitchIfEmpty<T>(this, nullCheck(other, "other is null")); }
java
public Image getSprite(int x, int y) { target.init(); initImpl(); if ((x < 0) || (x >= subImages.length)) { throw new RuntimeException("SubImage out of sheet bounds: "+x+","+y); } if ((y < 0) || (y >= subImages[0].length)) { throw new RuntimeException("SubImage out of sheet bounds: "+x+","+y); ...
java
private static boolean maybeLogRequest(RequestUri uri, Properties header, Properties parms) { LogFilterLevel level = LogFilterLevel.LOG; for (HttpLogFilter f : _filters) level = level.reduce(f.filter(uri, header, parms)); switch (level) { case DO_NOT_LOG: return false; // do not log the...
python
def download(self, files=None, formats=None, glob_pattern=None, dry_run=None, verbose=None, silent=None, ignore_existing=None, checksum=None, destdir=None, ...
java
public static byte[] base64decode( String coded ) { if ( null == coded ) return null; byte[] src = coded.getBytes(); int len = src.length; int dlen = len - (len/77); dlen = (dlen >>> 2) + (dlen >>> 1); int rem = 0; if ( 61 == src[ len - 1 ] ) ...
java
public List<String> getGroups(String username, String property) { final List<String> result = new ArrayList<>(); ldapTemplate.search(query().where("cn").is(username), new AttributesMapper<String>() { public String mapFromAttributes(Attributes attrs) throws NamingException { N...
java
public boolean rarFileExists() { final File zipFile = new File(rarFilePath); return AccessController.doPrivileged(new PrivilegedAction<Boolean>() { @Override public Boolean run() { return zipFile.exists(); } }); }
java
@Override public void actionCommit() { List<Throwable> errors = new ArrayList<Throwable>(); try { // set the synchronize settings CmsUserSettings userSettings = new CmsUserSettings(getCms()); m_synchronizeSettings.checkValues(getCms()); userSettings....
java
public static final void injectAll(final Object target, final Citrus citrusFramework) { injectAll(target, citrusFramework, citrusFramework.createTestContext()); }
python
def _lookup_attributes(glyph_name, data): """Look up glyph attributes in data by glyph name, alternative name or production name in order or return empty dictionary. Look up by alternative and production names for legacy projects and because of issue #232. """ attributes = ( data.names....
python
def random_uniform(attrs, inputs, proto_obj): """Draw random samples from a uniform distribtuion.""" try: from onnx.mapping import TENSOR_TYPE_TO_NP_TYPE except ImportError: raise ImportError("Onnx and protobuf need to be installed. " "Instructions to install - http...
java
public synchronized void putLong(long item) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "putLong", Long.valueOf(item)); checkValid(); getCurrentByteBuffer(4).putLong(item); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.ex...
python
def generate_json_artifacts(app, pagename, templatename, context, doctree): """ Generate JSON artifacts for each page. This way we can skip generating this in other build step. """ try: # We need to get the output directory where the docs are built # _build/json. build_json ...
python
def plot_windows(self, nwin, lmax=None, maxcolumns=3, tick_interval=[60, 45], minor_tick_interval=None, xlabel='Longitude', ylabel='Latitude', axes_labelsize=None, tick_labelsize=None, title_labelsize=None, grid=False, show=True, title=...
java
public static Pair<String, TypeName> searchInEachParameter(ModelMethod method, OnParameterListener listener) { for (Pair<String, TypeName> item : method.getParameters()) { if (listener.onParameter(item)) { return item; } } return null; }
java
@Override public boolean addAll(Collection<? extends T> c) { return c != null && !c.isEmpty() && indices.addAll(convert(c).indices); }
python
def get_sampling_strategy(self, sensor_name): """Get the current sampling strategy for the named sensor Parameters ---------- sensor_name : str Name of the sensor (normal or escaped form) Returns ------- strategy : tuple of str contains...
python
def _cast_message(self, message=None): '''Convert message data to :class:`Message` if needed, and merge with the default message. :param message: Message to merge with the default message. :rtype: :class:`Message` ''' if message is None: message = {} ...
python
def take_profit(self, accountID, **kwargs): """ Shortcut to create a Take Profit Order in an Account Args: accountID : The ID of the Account kwargs : The arguments to create a TakeProfitOrderRequest Returns: v20.response.Response containing the resul...
python
def load_model(ecore_model_path): """Load a single Ecore model and return the root package.""" rset = pyecore.resources.ResourceSet() uri_implementation = select_uri_implementation(ecore_model_path) resource = rset.get_resource(uri_implementation(ecore_model_path)) return resource.contents[0]
python
def get_dot(stop=True): """Returns a string containing a DOT file. Setting stop to True will cause the trace to stop. """ defaults = [] nodes = [] edges = [] # define default attributes for comp, comp_attr in graph_attributes.items(): attr = ', '.join( '%s = "%s"' % (attr...
java
public File export(String projectId, String language, FileTypeEnum fte, FilterByEnum[] filters){ return export(projectId, language, fte, filters, null, null); }
java
private TemporalAccessor toTemporal() { return new TemporalAccessor() { @Override public boolean isSupported(TemporalField field) { return false; } @Override public long getLong(TemporalField field) { throw new Unsupport...
java
public Stream partition(Grouping grouping) { if (_node instanceof PartitionNode) { return each(new Fields(), new TrueFilter()).partition(grouping); } else { return _topology.addSourcedNode(this, new PartitionNode(_node.streamId, _name, getOutputFields(), grouping)); } ...
java
public final void mRULE_RICH_TEXT_START() throws RecognitionException { try { int _type = RULE_RICH_TEXT_START; int _channel = DEFAULT_TOKEN_CHANNEL; // InternalSARL.g:16906:22: ( '\\'\\'\\'' ( RULE_IN_RICH_STRING )* ( '\\'' ( '\\'' )? )? '\\uFFFD' ) // InternalSA...
java
public static void cloneAll(Collection<BugInstance> dest, Collection<BugInstance> source) { for (BugInstance obj : source) { dest.add((BugInstance) obj.clone()); } }
java
public URI changesUri(String queryKey, Object queryValue) { if(queryKey.equals("since")){ if(!(queryValue instanceof String)){ //json encode the seq number since it isn't a string Gson gson = new Gson(); queryValue = gson.toJson(queryValue); ...
java
public static double spearmanRankCorrelationCoefficient(Vector a, Vector b) { return spearmanRankCorrelationCoefficient(Vectors.asDouble(a), Vectors.asDouble(b)); }
java
public static PersistenceBrokerSQLException generateException(SQLException ex, String sql, ClassDescriptor cld, Logger logger, Object obj) { return generateException(ex, sql, cld, null, logger, obj); }
python
def get(self, digest, chunk_size=1024 * 128): """ Return the contents of a blob :param digest: the hex digest of the blob to return :param chunk_size: the size of the chunks returned on each iteration :return: generator returning chunks of data """ return self.co...
python
def query(): """Query hot movies infomation from douban.""" r = requests_get(QUERY_URL) try: rows = r.json()['subject_collection_items'] except (IndexError, TypeError): rows = [] return MoviesCollection(rows)
python
def sismember(self, name, value): """Emulate sismember.""" redis_set = self._get_set(name, 'SISMEMBER') if not redis_set: return 0 result = self._encode(value) in redis_set return 1 if result else 0
java
@Override public boolean hasRemoteObjectWithPrefix(String appName, String moduleName, String compName, String namespaceString, String name) throws NamingException { boolean b = false; NamingConstants.JavaColonNamespace namespace = NamingConstants.JavaColonNamespace.fromName(namespaceString); ...
python
def convert_row(self, row, schema, fallbacks): """Convert row to BigQuery """ for index, field in enumerate(schema.fields): value = row[index] if index in fallbacks: value = _uncast_value(value, field=field) else: value = field....
java
public static Object get(Transferable content, DataFlavor flavor) { if (null != content && content.isDataFlavorSupported(flavor)) { try { return content.getTransferData(flavor); } catch (UnsupportedFlavorException | IOException e) { throw new UtilException(e); } } return null; }
python
def move_mouse_relative(self, x, y): """ Move the mouse relative to it's current position. :param x: the distance in pixels to move on the X axis. :param y: the distance in pixels to move on the Y axis. """ _libxdo.xdo_move_mouse_relative(self._xdo, x, y)
python
def as_list(x): '''Ensure `x` is of list type.''' if x is None: x = [] elif not isinstance(x, Sequence): x = [x] return list(x)
python
def dict_key_tag(Class, key, namespaces=None): """convert a dict key into an element or attribute name""" namespaces = namespaces or Class.NS ns = Class.tag_namespace(key) tag = Class.tag_name(key) if ns is None and ':' in key: prefix, tag = key.split(':') ...
java
public static String formatNodeProperties(String id, Node node, Map<String, Set<String>> uniqueConstraints, Set<String> indexNames, boolean jsonStyle) { StringBuilder result = formatProperties(id, node.getAllProperties(), jsonStyle); if (getNodeIdLabels(node, uniqueConstraints, indexNames).endsWith(labe...
python
def is_feature_enabled(self, feature): """Returns whether a particular recording feature is enabled for this screen or not. in feature of type :class:`RecordingFeature` Feature to check for. return enabled of type bool @c true if the feature is enabled, @c false...
java
public static TFloatList generateNormals(TFloatList positions, TIntList indices) { final TFloatList normals = new TFloatArrayList(); generateNormals(positions, indices, normals); return normals; }
python
def getProtocolClasses(superclass=message.Message): """ Returns all the protocol classes that are subclasses of the specified superclass. Only 'leaf' classes are returned, corresponding directly to the classes defined in the protocol. """ # We keep a manual list of the superclasses that we defin...
python
def forward_message(self, *args, **kwargs): """See :func:`forward_message`""" return forward_message(*args, **self._merge_overrides(**kwargs)).run()
java
public RouteMatcher deleteWithRegEx(String regex, Handler<HttpServerRequest> handler) { addRegEx(regex, handler, deleteBindings); return this; }
java
public void postRunnable (Runnable unit) { if (!_running) { log.warning("Posting runnable to inactive object manager", "unit", unit, new Exception()); } // just append it to the queue _evqueue.append(unit); }
java
public int verify(RRset set, Cache cache) { Iterator sigs = set.sigs(); if (Options.check("verbosesec")) System.out.print("Verifying " + set.getName() + "/" + Type.string(set.getType()) + ": "); if (!sigs.hasNext()) { if (Options.check("verbosesec")) System.out.println("Insecure"); return DNSSEC.Insecu...
java
private CmsResource findXmlPage(CmsObject cms, String resourcename) { // get the full folder path of the resource to start from String path = cms.getRequestContext().removeSiteRoot(resourcename); // the path without the trailing slash // for example: .../xmlpage.xml/ -> .../xmlpagepage....
java
protected String redefineArgsIfNeeds(String formatString) { if (!formatString.contains("{") || !formatString.contains("}")) { // no parameter return formatString; } final List<ScopeInfo> plainVariableList = Srl.extractScopeList(formatString, "{", "}"); if (!plainVariableList....
python
def get_key(): """Get a key from the keyboard as a string A 'key' will be a single char, or the name of an extended key """ character_name = chr codes = _get_keycodes() if len(codes) == 1: code = codes[0] if code >= 32: return character_name(code) return cont...
python
def as_chord(chord): """ convert from str to Chord instance if input is str :type chord: str|pychord.Chord :param chord: Chord name or Chord instance :rtype: pychord.Chord :return: Chord instance """ if isinstance(chord, Chord): return chord elif isinstance(chord, str): ...
python
def merge(d1, d2): """This method does cool stuff like append and replace for dicts d1 = { "steve": 10, "gary": 4 } d2 = { "&steve": 11, "-gary": null } result = { "steve": [10, 11] } """ d1, d2 = deepcopy(d1),...
java
@Override public Object newInstance( final Class<Object> cls, final InputElement xml ) throws XMLStreamException { final Class<?> superclass; try { superclass = Class.forName( xml.getAttribute( SUPERCLASS ).toString() ); } catch ( final ClassNotFoundException e ) { th...
java
public KeyStore newInstance() throws KeyStoreException, NoSuchProviderException, NoSuchAlgorithmException, CertificateException, IOException { if (data == null) { throw new IllegalStateException("data property is not set."); } KeyStore ks; if (provider == null) { ...
java
public ValidationResult check(Entry entry) { result = new ValidationResult(); if (entry == null) { return result; } String dataClass = entry.getDataClass(); if (dataClass != null && dataClass.equals(Entry.PRT_DATACLASS)) { return result; ...
java
@Override public DescribeEnvironmentManagedActionHistoryResult describeEnvironmentManagedActionHistory(DescribeEnvironmentManagedActionHistoryRequest request) { request = beforeClientExecution(request); return executeDescribeEnvironmentManagedActionHistory(request); }
java
public static String getText(Path self, String charset) throws IOException { return IOGroovyMethods.getText(newReader(self, charset)); }
java
@Override public void authenticateWithBlackduck() throws IntegrationException { final URL authenticationUrl; try { authenticationUrl = new URL(getBaseUrl(), "api/tokens/authenticate"); } catch (final MalformedURLException e) { throw new IntegrationException("Error con...
java
public void setProperties(Properties properties) { config.setProperties(properties); //注册解析器 if (properties != null) { String resolveClass = properties.getProperty("resolveClass"); if (StringUtil.isNotEmpty(resolveClass)) { try { Entity...
python
def compute_lengths(sequence_data: mx.sym.Symbol) -> mx.sym.Symbol: """ Computes sequence lengths of PAD_ID-padded data in sequence_data. :param sequence_data: Input data. Shape: (batch_size, seq_len). :return: Length data. Shape: (batch_size,). """ return mx.sym.sum(sequence_data != C.PAD_ID, ...
java
public static void transposeSquare( BMatrixRMaj mat ) { if( mat.numCols != mat.numRows ) throw new IllegalArgumentException("Must be sqare"); int index = 1; int indexEnd = mat.numCols; for( int i = 0; i < mat.numRows; i++ , index += i+1 , indexEnd += mat.num...
java
public Field getField(String name) { if (fieldMap == null) { return null; } return fieldMap.get(name); }
java
@InterfaceAudience.Public public boolean clearAuthenticationStores() { if (getAuthenticator() != null) { if (!(getAuthenticator() instanceof Authorizer) || !((Authorizer) getAuthenticator()).removeStoredCredentials()) return false; } else { ...
python
def _start_collective_solver(self, state): ''' Determines who from all the monitors monitoring this agent should resolve the issue. ''' own_address = state.agent.get_own_address() monitors = [IRecipient(x) for x in state.descriptor.partners if x.role =...
python
def _set_player(self): """ Sort the current players into priority order and set self._player Players are ordered by working state then prefernce supplied by user and finally by instance if a player has more than one running. """ players = [] for name, p in self._m...
python
def name(self) -> str: """OpenSSL uses a different naming convention than the corresponding RFCs. """ return OPENSSL_TO_RFC_NAMES_MAPPING[self.ssl_version].get(self.openssl_name, self.openssl_name)
python
def Chisholm_voidage(x, rhol, rhog): r'''Calculates void fraction in two-phase flow according to the model of [1]_, as given in [2]_ and [3]_. .. math:: \alpha = \left[1 + \left(\frac{1-x}{x}\right)\left(\frac{\rho_g} {\rho_l}\right)\sqrt{1 - x\left(1-\frac{\rho_l}{\rho_g}\right)} ...
python
def getLookupTable(self, img=None, n=None, alpha=None): """Return a lookup table from the color gradient defined by this HistogramLUTItem. """ if n is None: if img.dtype == np.uint8: n = 256 else: n = 512 if self.lut is None...
java
public static Map<String, Collection<String>> splitDeviceEntities(final Collection<String> entityNames) { final Map<String, Collection<String>> result = new HashMap<String, Collection<String>>(); String device; String entity; for (final String entityName : entityNames) { try...
python
def _handle_rfx(self, data): """ Handle RF messages. :param data: RF message to parse :type data: string :returns: :py:class:`~alarmdecoder.messages.RFMessage` """ msg = RFMessage(data) self.on_rfx_message(message=msg) return msg
python
def unquote(text): """Replace all percent-encoded entities in text.""" while '%' in text: newtext = url_unquote(text) if newtext == text: break text = newtext return text
java
private String[] readMultiMapValuesForKey(XMLEventReader reader) throws XMLStreamException, JournalException { List<String> values = new ArrayList<String>(); while (true) { XMLEvent event = reader.nextTag(); if (isStartTagEvent(event, QNAME_TAG_MULTI_VALUE_MAP_VALUE))...
java
public boolean canScheduleStage(PipelineIdentifier pipelineIdentifier, String stageName, String username, final OperationResult result) { String pipelineName = pipelineIdentifier.getName(); CompositeChecker checker = buildScheduleCheckers(asList( new S...