language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static long[] hashToLongs(final String datum, final long seed) { if ((datum == null) || datum.isEmpty()) { return null; } final byte[] data = datum.getBytes(UTF_8); return hash(data, seed); }
python
def start(name=None, id=None, bootpath=None, disk=None, disks=None, local_iface=False, memory=None, nics=0, switch=None): ''' Starts a VM defined by the specified parameters. When both a name and id are provided, the id is ignored. name: Name of the defined VM. id: VM id....
python
def _datetime_to_utc(self, dt): """Convert naive datetimes to UTC""" if not dt.tzinfo: dt = dt.replace(tzinfo=tz.gettz()) return dt.astimezone(tz.gettz('UTC'))
java
public static InsnList saveOperandStack(MarkerType markerType, StorageVariables storageVars, Frame<BasicValue> frame, int count) { Validate.notNull(markerType); Validate.notNull(storageVars); Validate.notNull(frame); Validate.isTrue(count >= 0); Validate.isTrue(count <= frame.get...
python
def convert_numpy_str_to_uint32(data): """ Converts a numpy.unicode\_ to its numpy.uint32 representation. Convert a ``numpy.unicode_`` or an array of them (they are UTF-32 strings) into the equivalent array of ``numpy.uint32`` that is byte for byte identical. Strings are expanded along rows (across col...
python
def build_imputation_loyers_proprietaires(temporary_store = None, year = None): """Build menage consumption by categorie fiscale dataframe """ assert temporary_store is not None assert year is not None # Load data bdf_survey_collection = SurveyCollection.load(collection = 'budget_des_familles', ...
python
def validate(sampler, replicates=20, iterations=10000, burn=5000, thin=1, deterministic=False, db='ram', plot=True, verbose=0): """ Model validation method, following Cook et al. (Journal of Computational and Graphical Statistics, 2006, DOI: 10.1198/106186006X136976). Generates posterior s...
python
def wrapper__unignore(self, type_): """ Stop selectively ignoring certain types when wrapping attributes. :param class type: The class/type definition to stop ignoring. :rtype list(type): The current list of ignored types """ if type_ in self.__exclusion_list: ...
java
protected void afterInvoke(Method method, Object[] params) throws Exception { // Close the session if (session != null) { session.close(); } }
java
protected static void writeIterator(Output out, Iterator<Object> it) { log.trace("writeIterator"); // Create LinkedList of collection we iterate thru and write it out later LinkedList<Object> list = new LinkedList<Object>(); while (it.hasNext()) { list.addLast(it.next()); ...
python
def ParseFileDownloadedRow( self, parser_mediator, query, row, **unused_kwargs): """Parses a file downloaded row. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. query (str): query that created the row. ...
java
public void addRange(byte[] startRow, byte[] stopRow) { addRange(RowRange.newBuilder() .setStartKeyClosed(ByteStringer.wrap(startRow)) .setEndKeyOpen(ByteStringer.wrap(stopRow)) .build()); }
java
@NotNull public static <T> Collector<T, ?, Double> averagingInt(@NotNull final ToIntFunction<? super T> mapper) { return averagingHelper(new BiConsumer<long[], T>() { @Override public void accept(long[] t, T u) { t[0]++; // count t[1] += mapper.applyAs...
python
def _outer_to_numpy_indexer(key, shape): """Convert an OuterIndexer into an indexer for NumPy. Parameters ---------- key : Basic/OuterIndexer An indexer to convert. shape : tuple Shape of the array subject to the indexing. Returns ------- tuple Tuple suitable fo...
java
@Override public <T> T get(String name, Class<T> type) { return this.properties.get(name, type); }
java
public <T extends InteractionAwareFixture> T create(Class<T> clazz, Class<?>[] constructorTypes, Object[] constructorArgs) { MethodInterceptor callback = createCallback(); T result; if (FACTORIES.containsKey(clazz)) { Factory factory = FACTORIES.get(clazz); result = crea...
python
def run(self): """ Main entry function. """ history = InMemoryHistory() self._load_file() while True: # (re)load the todo.txt file (only if it has been modified) try: user_input = prompt(u'topydo> ', history=history, ...
java
public Map<String, EnumSet<Permissions>> getPermissions() { JsonObject perms = getPermissionsObject(); return client.getGson().getAdapter(DeserializationTypes.PERMISSIONS_MAP_TOKEN).fromJsonTree (perms); }
java
public Boolean assignUsersToPrivilege(String id, List<Long> userIds) throws OAuthSystemException, OAuthProblemException, URISyntaxException { cleanError(); prepareToken(); OneloginURLConnectionClient httpClient = new OneloginURLConnectionClient(); OAuthClient oAuthClient = new OAuthClient(httpClient); URIBu...
java
public CompensatingTransactionOperationRecorder createRecordingOperation(Object resource, String operation) { if (ObjectUtils.nullSafeEquals(operation, LdapTransactionUtils.BIND_METHOD_NAME)) { log.debug("Bind operation recorded"); return new BindOperationRecorder(createLdapOperationsInstance((DirContext) resou...
java
public static <T> Observable<T> deferFuture(Func0<? extends Future<? extends Observable<? extends T>>> observableFactoryAsync) { return OperatorDeferFuture.deferFuture(observableFactoryAsync); }
java
@Override public int getMinPrefixLengthForBlock() { Integer result; if(hasNoPrefixCache() || (result = prefixCache.cachedMinPrefix) == null) { prefixCache.cachedMinPrefix = result = cacheBits(super.getMinPrefixLengthForBlock()); } return result; }
java
public List<WsByteBuffer> finish() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, "finish"); } List<WsByteBuffer> list = new LinkedList<WsByteBuffer>(); if (isFinished()) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEn...
java
public void updateBinaryRepresenation() { // check whether the binary state is in sync final int firstModified = this.firstModifiedPos; if (firstModified == Integer.MAX_VALUE) { return; } final InternalDeSerializer serializer = this.serializer; final int[] offsets = this.offsets; final int numFields...
python
def from_millis(cls, timeout_ms): """Create a new PolledTimeout if needed. If timeout_ms is already a PolledTimeout, just return it, otherwise create a new PolledTimeout with the given timeout in milliseconds. Args: timeout_ms: PolledTimeout object, or number of milliseconds to use for c...
python
def content_create(self, key, model, contentid, meta, protected=False): """Creates a content entity bucket with the given `contentid`. This method maps to https://github.com/exosite/docs/tree/master/provision#post---create-content-entity. Args: key: The CIK or Token for the...
java
public static <U> CompletableFuture<U> completedFuture(U value) { return new CompletableFuture<U>((value == null) ? NIL : value); }
python
def front(self, *fields): '''Return the front pair of the structure''' ts = self.irange(0, 0, fields=fields) if ts: return ts.start(), ts[0]
python
def get_species(taxdump_file, select_divisions=None, exclude_divisions=None, nrows=None): """Get a dataframe with species information.""" if select_divisions and exclude_divisions: raise ValueError('Cannot specify "select_divisions" and ' '"exclude_divisions...
java
@Indexable(type = IndexableType.REINDEX) @Override public CPDefinitionSpecificationOptionValue updateCPDefinitionSpecificationOptionValue( CPDefinitionSpecificationOptionValue cpDefinitionSpecificationOptionValue) { return cpDefinitionSpecificationOptionValuePersistence.update(cpDefinitionSpecificationOptionValue...
python
def load_url(self, url=None, verbose=False): """ Load a new network from a URL that points to a network file type (e.g. SIF, XGMML, etc.). Use network import url to load networks from Excel or csv files. This command will create a new network collection if no current network coll...
python
def Trim(self): """ Returns a byte array that contains only the block header and transaction hash. Returns: bytes: """ ms = StreamManager.GetStream() writer = BinaryWriter(ms) self.SerializeUnsigned(writer) writer.WriteByte(1) self.Scr...
java
@Override public CommerceTaxFixedRate remove(Serializable primaryKey) throws NoSuchTaxFixedRateException { Session session = null; try { session = openSession(); CommerceTaxFixedRate commerceTaxFixedRate = (CommerceTaxFixedRate)session.get(CommerceTaxFixedRateImpl.class, primaryKey); if (commerc...
java
@Override public void loadArgs(List<String> arguments) { if(arguments == null || arguments.isEmpty()) return; this.setProperties(ArgsParser.parse(arguments)); }
python
def listen(cls, event, func): """Add a callback for a signal against the class""" signal(event).connect(func, sender=cls)
java
@Override public String writeSingle(String key) throws Exception { MutationBatch m = keyspace.prepareMutationBatch().withConsistencyLevel(ConsistencyLevel.valueOf(config.getWriteConsistencyLevel())); ColumnListMutation<Integer> colsMutation = m.withRow(this.CF, key); for (int i = 0; i < co...
java
@Override public List<CPMeasurementUnit> findAll(int start, int end) { return findAll(start, end, null); }
python
def cbox(i, gray=False, spectrum="alternate", reverse=False, **kwargs): """ Access a modular list of colors for plotting. Defines colours using rgb. :param i: (int), index to access color :param gray: (bool), if true then color is return as grayscale value :param spectrum: (str), choice of spec...
java
public void marshall(KeyProviderSettings keyProviderSettings, ProtocolMarshaller protocolMarshaller) { if (keyProviderSettings == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(keyProviderSettings.ge...
java
public void perform(TaskRequest req, TaskResponse res) { HttpServletResponse resp = (HttpServletResponse) response.evaluate(req, res); Integer sc = (Integer) statusCode.evaluate(req, res); resp.setStatus(sc); }
java
public List<EventSubscriptionInner> listByResource(String resourceGroupName, String providerNamespace, String resourceTypeName, String resourceName) { return listByResourceWithServiceResponseAsync(resourceGroupName, providerNamespace, resourceTypeName, resourceName).toBlocking().single().body(); }
java
public SubscriptionQos setValidityMs(final long validityMs) { if (validityMs == -1) { setExpiryDateMs(NO_EXPIRY_DATE); } else { long now = System.currentTimeMillis(); this.expiryDateMs = now + validityMs; } return this; }
java
public String getRemoteEngineUuid() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "getRemoteEngineUuid"); String remoteMEId = aoBrowserSession.getKey().getRemoteMEUuid().toString(); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) ...
python
def return_future(f): """Decorator to make a function that returns via callback return a `Future`. The wrapped function should take a ``callback`` keyword argument and invoke it with one argument when it has finished. To signal failure, the function can simply raise an exception (which will be ...
python
def convert_to_gt( text, layer_name=GT_WORDS ): ''' Converts all words in a morphologically analysed Text from FS format to giellatekno (GT) format, and stores in a new layer named GT_WORDS. If the keyword argument *layer_name=='words'* , overwrites the old 'words' layer with the new laye...
python
def close(self): """ Closes the connection and any tunnels created for it. """ try: super(DockerFabricClient, self).close() finally: if self._tunnel is not None: self._tunnel.close()
python
def get(self, key, range_end=None, count_only=None, keys_only=None, limit=None, max_create_revision=None, min_create_revision=None, min_mod_revision=None, revision=None, serializable=None, ...
java
@GET public List<IAgreement> getAgreements( @QueryParam("consumerId") String consumerId, @QueryParam("providerId") String providerId, @QueryParam("templateId") String templateId, @QueryParam("active") BooleanParam active) { logger.debug("StartOf getAgreements ...
python
def reset_weights(self): """ Initialize properly model weights """ self.input_block.reset_weights() self.policy_backbone.reset_weights() self.value_backbone.reset_weights() self.action_head.reset_weights() self.value_head.reset_weights()
python
def calcul_distance(*args): """ ;+ ; CALCUL_DISTANCE : fonction permettant de calculer la distance entre deux points sur la sphere ; ; @Author : Mathilde FAILLOT (LEGOS/CTOH), 2005 ; @History : ; - 2005 : First release, source:<br /> ; Weisstein, Eric W. "Great Cir...
java
public void start() { if (scheduler == null) { if (enabled) { Scheduler.Options options = new Scheduler.Options() .withFrequency(Scheduler.Policy.FIXED_DELAY, frequency) .withInitialDelay(frequency) .withStopOnFailure(false); scheduler = new Scheduler(this, ...
python
def imview(img, title=None, copy=True, fltscl=False, intrp='nearest', norm=None, cbar=False, cmap=None, fgsz=None, fgnm=None, fig=None, ax=None): """ Display an image. Pixel values are displayed when the pointer is over valid image data. If a figure object is specified then the image ...
python
def listen_dep(self, target, timeout): """Listen *timeout* seconds to become initialized as a DEP Target. The RC-S956 can be set to listen as a DEP Target for passive communication mode. Target active communication mode is disabled by the driver due to performance issues. It is also ...
java
public static Analysis readAnalysis(final URL url) throws IOException { checkNotNull(url); try (BufferedReader reader = Resources.asCharSource(url, Charsets.UTF_8).openBufferedStream()) { return readAnalysis(reader); } }
python
def datadir_init(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, waldir=None, checksums=False, runas=None): ''' .. versionadded:: 2016.3.0 Initializes a postgres data directory CLI Example: .. code-bloc...
java
private void updateToolTipDialogVisibility() { // Determine whether tooltip should be/remain visible boolean shouldBeVisible = isOverDecorationPainter() || isOverToolTipDialog(); // Create tooltip dialog if needed if (shouldBeVisible) { createToolTipDialogIfNeeded(); ...
java
public CmsClientProperty getEffectivePropertyObject(CmsClientSitemapEntry entry, String name) { Map<String, CmsClientProperty> dfProps = entry.getDefaultFileProperties(); CmsClientProperty result = safeLookup(dfProps, name); if (!CmsClientProperty.isPropertyEmpty(result)) { return r...
python
def get_script_str(self, reset=True): """Returns a string with the script and reset the editor if reset is True""" s = "\n".join(l for l in self._lines) if reset: self.reset() return s
java
protected Node bulkConstruct(DBIDRef cur, int maxScale, double parentDist, ModifiableDoubleDBIDList elems) { assert (!elems.contains(cur)); final double max = maxDistance(elems); final int scale = Math.min(distToScale(max) - 1, maxScale); final int nextScale = scale - 1; // Leaf node, because points...
java
public static Expression arrayPosition(JsonArray array, Expression value) { return arrayPosition(x(array), value); }
python
def add_xy(self, x, y): """ Add an motor order/sensory effect pair to the model :arg x: an input (order) vector compatible with self.Mfeats. :arg y: a output (effect) vector compatible with self.Sfeats. """ self.imodel.add_xy(self._pre_x(x), self._pre_y(y))
java
static long parseServerDurationFromFrame(final ByteBuf frame) { while(frame.readableBytes() > 0) { byte control = frame.readByte(); byte id = (byte) (control & 0xF0); byte len = (byte) (control & 0x0F); if (id == FRAMING_EXTRAS_TRACING) { return Ma...
python
def show_results(self, ds_type=DatasetType.Valid, rows:int=5, max_len:int=20): from IPython.display import display, HTML "Show `rows` result of predictions on `ds_type` dataset." ds = self.dl(ds_type).dataset x,y = self.data.one_batch(ds_type, detach=False, denorm=False) preds = ...
java
public static <T> Collection<T> addAll(Collection<T> to, Collection<? extends T> what) { Collection<T> data = safeCollection(to); if (!isEmpty(what)) { data.addAll(what); } return data; }
java
public RootNode parseInternal(StringBuilderVar block) { char[] chars = block.getChars(); int[] ixMap = new int[chars.length + 1]; // map of cleaned indices to original indices // strip out CROSSED_OUT characters and build index map StringBuilder clean = new StringBuilder(); ...
java
private void addEntry(final Path pathToFile, final URL resource) throws IOException { final Path parent = pathToFile.getParent(); if (parent != null) { addFolder(parent); } try (InputStream inputStream = resource.openStream()) { Files.copy(inputStream, pathToFile...
python
def compile_authors(authors): """ Compiles authors "Last, First" into a single list :param list authors: Raw author data retrieved from doi.org :return list: Author objects """ author_list = [] for person in authors: author_list.append({'name': person['family'] + ", " + person['given...
python
def bytes_to_char(arr): """Convert numpy/dask arrays from fixed width bytes to characters.""" if arr.dtype.kind != 'S': raise ValueError('argument must have a fixed-width bytes dtype') if isinstance(arr, dask_array_type): import dask.array as da return da.map_blocks(_numpy_bytes_to_...
java
public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case STATUS: return isSetStatus(); case OPERATION_STATE: return isSetOperationState(); case SQL_STATE: return isSetSqlState(); case ERROR_CODE: r...
java
public void deleteColumn(int column) throws BadElementException { float newWidths[] = new float[--columns]; System.arraycopy(widths, 0, newWidths, 0, column); System.arraycopy(widths, column + 1, newWidths, column, columns - column); setWidths(newWidths); System.arraycopy(widths,...
python
def island_itergen(catalog): """ Iterate over a catalog of sources, and return an island worth of sources at a time. Yields a list of components, one island at a time Parameters ---------- catalog : iterable A list or iterable of :class:`AegeanTools.models.OutputSource` objects. Yi...
python
def endline_repl(self, inputstring, reformatting=False, **kwargs): """Add end of line comments.""" out = [] ln = 1 # line number for line in inputstring.splitlines(): add_one_to_ln = False try: if line.endswith(lnwrapper): line...
java
public static <T> Handler<T> mdc(final Handler<T> handler) { if (handler == null) { // Throw here instead of getting NPE inside the handler so we can see the stack trace throw new IllegalArgumentException("handler may not be null"); } final Map<String, String> mdc = MDC.getCopyOfContextMap(); ...
python
def not_implemented(cls, errors=None): """Shortcut API for HTTP 501 `Not Implemented` response. Args: errors (list): Response key/value data. Returns: WSResponse Instance. """ if cls.expose_status: # pragma: no cover cls.response.content_typ...
python
def dir_df_boot(dir_df, nb=5000, par=False): """ Performs a bootstrap for direction DataFrame with optional parametric bootstrap Parameters _________ dir_df : Pandas DataFrame with columns: dir_dec : mean declination dir_inc : mean inclination Required for parametric bootstrap...
python
def _setSampleSizeBytes(self): """ updates the current record of the packet size per sample and the relationship between this and the fifo reads. """ self.sampleSizeBytes = self.getPacketSize() if self.sampleSizeBytes > 0: self.maxBytesPerFifoRead = (32 // self.sampl...
java
public Observable<List<AzureResourceSkuInner>> listSkusByResourceAsync(String resourceGroupName, String clusterName) { return listSkusByResourceWithServiceResponseAsync(resourceGroupName, clusterName).map(new Func1<ServiceResponse<List<AzureResourceSkuInner>>, List<AzureResourceSkuInner>>() { @Overr...
java
@Override public long dynamicQueryCount(DynamicQuery dynamicQuery, Projection projection) { return cpOptionCategoryPersistence.countWithDynamicQuery(dynamicQuery, projection); }
python
def show_entry_map(self): """ Show entry map for a package @param dist: package @param type: srting @returns: 0 for success or 1 if error """ pprinter = pprint.PrettyPrinter() try: entry_map = pkg_resources.get_entry_map(self.options.show_ent...
java
@SuppressWarnings("unchecked") @NonNull public static Set<String> nonNullSet(@Nullable String[] items) { return items == null || items.length == 0 ? Collections.<String>emptySet() : new HashSet<String>(asList(items)); }
java
@Override public void check(Connection conn, String scName, Collection<String> tbNames) throws IllegalMetaDataException { if (scName == null) { throw new IllegalArgumentException("[Check MetaData Failed] parameter 'scName' can't be null"); } if (tbNames == null || tbNames.isEmpty...
java
public static String getPropertyName(String propertyPath) { int propertySeparatorIndex = PropertyAccessorUtils.getLastNestedPropertySeparatorIndex(propertyPath); return propertySeparatorIndex == -1? propertyPath: propertyPath.substring(propertySeparatorIndex + 1); }
java
public T setOpenTagLocation(SourceLocation location) { checkState(openTagLocation == null); this.openTagLocation = checkNotNull(location); return (T) this; }
java
@Override public Map<String, Double> extract(final String text) { Map<Integer, String> ID2word = new HashMap<>(); //ID=>Kwd Map<Integer, Double> ID2occurrences = new HashMap<>(); //ID=>counts/scores Map<Integer, Integer> position2ID = new LinkedHashMap<>(); //word position=>ID maintain the o...
java
public static void main(String[] argv) throws IOException { if (argv.length != 2) { System.err.println("Wrong parameters, exit immediately"); return; } ChronosClient chronosClient = null; try { chronosClient = new ChronosClient(argv[0], argv[1]); System.out.println("Get time...
python
def fmt_camel(name): """ Converts name to lower camel case. Words are identified by capitalization, dashes, and underscores. """ words = split_words(name) assert len(words) > 0 first = words.pop(0).lower() return first + ''.join([word.capitalize() for word in words])
python
def resolve_attribute(name, bases, default=None): """Find the first definition of an attribute according to MRO order.""" for base in bases: if hasattr(base, name): return getattr(base, name) return default
java
public AndCondition copy() { AndCondition builder = new AndCondition(); builder.children.addAll(children); return builder; }
python
def symmetric_rescaling_sa(A, B, BH=None): """Scale the matrix symmetrically. A = D^{-1/2} A D^{-1/2} where D=diag(A). The left multiplication is accomplished through scale_rows and the right multiplication is done through scale columns. The candidates B and BH are scaled accordingly:: ...
python
def to_text(path, bucket_name='cloud-vision-84893', language='fr'): """Sends PDF files to Google Cloud Vision for OCR. Before using invoice2data, make sure you have the auth json path set as env var GOOGLE_APPLICATION_CREDENTIALS Parameters ---------- path : str path of electronic invo...
java
@Activated public void configure() { String persistenceUnit = configuration.get("persistenceUnit"); if (persistenceUnit == null) { PersistenceXMLProcessor processor = new PersistenceXMLProcessor(); processor.process(); List<String> persistenceUnits = processor.persistenceUnits(); if (persistence...
java
public final String getStringDefault(String defaultValue, String attribute, String... path) { return getNodeStringDefault(defaultValue, attribute, path); }
python
def _reorder_columns(bed_file): """ Reorder columns to be compatible with CoRaL """ new_bed = utils.splitext_plus(bed_file)[0] + '_order.bed' with open(bed_file) as in_handle: with open(new_bed, 'w') as out_handle: for line in in_handle: cols = line.strip().split(...
java
PointL buildPathPortion(final Projection pProjection, final PointL pOffset, final boolean pStorePoints){ final int size = mOriginalPoints.size(); if (size < 2) { // nothing to paint return pOffset; } computeProjected(pProjection); computeDistances(); final PointL offset; if (p...
python
def read_geojson(filename): """ Reads a geojson file containing an STObject and initializes a new STObject from the information in the file. Args: filename: Name of the geojson file Returns: an STObject """ json_file = open(filename) data = json.load(json_file) json_fil...
java
@Override public <T> long insertObjects(Collection<T> coll) throws CpoException { return processUpdateGroup(coll, CpoAdapter.CREATE_GROUP, null, null, null, null); }
java
public static Message buildFileReceived(String fullPath) { ZabMessage.FileReceived received = ZabMessage.FileReceived .newBuilder() .setFullPath(fullPath) .build(); ...
java
public final void unlock(Object lockObject) { // Only unlock the bean instance if it is in a state where it can be // made eligible for use on other threads. For example, for CM, this // might be when no longer in a transaction; for BM, this might be // when not in a method, etc. ...
python
def delete_simple_httpauth_read_api( request, database_name, collection_name, slug): """Delete Simple PublicReadAPI""" ss = get_object_or_404(HTTPAuthReadAPI, database_name=database_name, collection_name=collection_name, slug=slug) ss.delete() m...
python
def __SetBody(self, http_request, method_config, request, upload): """Fill in the body on http_request.""" if not method_config.request_field: return request_type = _LoadClass( method_config.request_type_name, self.__client.MESSAGES_MODULE) if method_config.reque...