language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static <A> FutureCallback<A> futureCallback(final Action<A> success, final Action<Throwable> failure) { return new FutureCallback<A>() { @Override public void onSuccess(A result) { checkNotNull(success).apply(result); } @Override public void onFailure(...
java
int getAbsoluteOffset(int index) throws JMFUninitializedAccessException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) JmfTr.entry(this, tc, "getAbsoluteOffset", new Object[]{Integer.valueOf(index)}); MessageMap.Remap remap = map.fields[index]; if (remap == null) { if (TraceCompo...
python
def config_mode(self, config_command="", pattern=""): """Enter into config_mode. :param config_command: Configuration command to send to the device :type config_command: str :param pattern: Pattern to terminate reading of channel :type pattern: str """ output = ...
python
def text_normalize(text): """ Whitespace normalization: - Strip empty lines - Strip leading whitespace in a line - Strip trailing whitespace in a line - Normalize line endings """ # if not isinstance(text, str): if isinstance(text, bytes): # -- MAYBE: command.ouput ...
python
def build_database_sortmerna(fasta_path, max_pos=None, output_dir=None, temp_dir=tempfile.gettempdir(), HALT_EXEC=False): """ Build sortmerna db from fasta_path; return db name and list of fil...
python
def _compile_iterable(self, schema): """ Compile iterable: iterable of schemas treated as allowed values """ # Compile each member as a schema schema_type = type(schema) schema_subs = tuple(map(self.sub_compile, schema)) # When the schema is an iterable with a single item (e.g. ...
java
protected RedirectView connectionStatusRedirect(String providerId, NativeWebRequest request) { HttpServletRequest servletRequest = request.getNativeRequest(HttpServletRequest.class); String path = connectionStatusUrlPath + providerId + getPathExtension(servletRequest); if (prependServletPath(servletRequest)) { ...
python
def transpose(self, semitone): """ Transpose the pianorolls of all tracks by a number of semitones, where positive values are for higher key, while negative values are for lower key. The drum tracks are ignored. Parameters ---------- semitone : int Th...
python
def evaluate(ref_intervals, ref_pitches, ref_velocities, est_intervals, est_pitches, est_velocities, **kwargs): """Compute all metrics for the given reference and estimated annotations. Parameters ---------- ref_intervals : np.ndarray, shape=(n,2) Array of reference notes time inte...
python
def update_picks(self, games=None, points=None): ''' games can be dict of {game.id: winner_id} for all picked games to update ''' if games: game_dict = {g.id: g for g in self.gameset.games.filter(id__in=games)} game_picks = {pick.game.id: pick for pick in self.gam...
java
public void reload(Environment environment) { Properties configuration = underlyingSource.getConfiguration(environment); cachedConfigurationPerEnvironment.put(environment.getName(), configuration); }
python
def reindex_repo_dev_panel(self, project, repository): """ Reindex all of the Jira issues related to this repository, including branches and pull requests. This automatically happens as part of an upgrade, and calling this manually should only be required if something unforeseen happens ...
java
public void setIdentity(String name, String email) { if (GitTaskUtils.isNullOrBlankString(name) || GitTaskUtils.isNullOrBlankString(email)) { throw new IllegalArgumentException("Both the username and password must be provided."); } identity = new ...
java
private static String encodeUrlPart(final String part) throws UnsupportedEncodingException { //we need to go through and check part by part that a section does not need encoding int pos = 0; for (int i = 0; i < part.length(); ++i) { char c = part.charAt(i); if(c == '?') ...
java
public HttpCall<Void> newCall() { HttpUrl url = pipeline != null ? http.baseUrl.newBuilder("_bulk").addQueryParameter("pipeline", pipeline).build() : http.baseUrl.resolve("_bulk"); Request request = new Request.Builder() .url(url) .tag(tag) ...
python
def new(self, filename=None): """start a session an independent process""" path = (self.exec_path,) if self.exec_path.filetype() in ('py', 'pyw', 'pyz', self.FTYPE): # get the absolute path to the python-executable p = find_executable("python") path = (p...
java
private boolean locationAwareLog(int level_int, String msgTemplate, Object[] arguments) { return locationAwareLog(level_int, null, msgTemplate, arguments); }
java
@Deprecated public static <T> T load(File file, Class<T> configClass) throws Exception { Preconditions.checkNotNull(file, "file"); Preconditions.checkNotNull(configClass, "clazz"); return new ConfigurationLoader(file.getParentFile()).load(configClass, file.getName()); }
python
def get_hdrs(self, **kws): """Initialize column headers.""" hdrs = get_hdrs(self.prt_flds, **kws) # Values in a "format_txt" "column" are used for formatting, not printing return [h for h in hdrs if h != "format_txt"]
java
public static OdsFactory create(final Logger logger, final Locale locale) { final PositionUtil positionUtil = new PositionUtil(new EqualityUtil(), new TableNameUtil()); final WriteUtil writeUtil = WriteUtil.create(); final XMLUtil xmlUtil = XMLUtil.create(); final DataStyles format =...
python
def debug(self): # pragma: no cover """Prints all configuration registries for debugging purposes.""" print("Aliases:") pprint.pprint(self._aliases) print("Override:") pprint.pprint(self._override) print("Args:") pprint.pprint(self._args) print("Env:") ...
java
public static String printRules() { theRules.get(0).getSAXRules(); expandRules(); Vector<SAXRule> rules = new Vector<SAXRule>(numRules.intValue()); SAXRule currentRule; SAXRule referedTo; SAXSymbol sym; int index; int processedRules = 0; StringBuilder text = new StringBu...
java
public double[] normOne(double[] data) { double[] res = new double[data.length]; double max = max(data); for (int i = 0; i < data.length; i++) { res[i] = data[i] / max; } return res; }
java
public void step(Context ctxt, ILexLocation location) { if (Settings.dialect == Dialect.VDM_RT) { if (!virtual) { duration(getObject().getCPU().getDuration(Properties.rt_cycle_default), ctxt, location); } } else { SystemClock.advance(Properties.rt_duration_default); } // Note that we don't...
java
public static FullTypeSignature getTypeSignature(String typeSignatureString, boolean useInternalFormFullyQualifiedName) { String key; if (!useInternalFormFullyQualifiedName) { key = typeSignatureString.replace('.', '/') .replace('$', '.'); } else { key = typeSignatureString; } // we always use ...
java
public ServiceCall<Gateway> getGateway(GetGatewayOptions getGatewayOptions) { Validator.notNull(getGatewayOptions, "getGatewayOptions cannot be null"); String[] pathSegments = { "v1/environments", "gateways" }; String[] pathParameters = { getGatewayOptions.environmentId(), getGatewayOptions.gatewayId() }; ...
java
public static void escapeJson(final String text, final Writer writer, final JsonEscapeType type, final JsonEscapeLevel level) throws IOException { if (writer == null) { throw new IllegalArgumentException("Argument 'writer' cannot be null"); } ...
python
def run(self, input_fname, ids_per_job, stagger=0, **wait_params): """Run this submission all the way. This method will run both `submit_reading` and `watch_and_wait`, blocking on the latter. """ submit_thread = Thread(target=self.submit_reading, a...
java
public <R> R toListAndThen(Function<? super List<T>, R> finisher) { if (context.fjp != null) return context.terminate(() -> finisher.apply(toList())); return finisher.apply(toList()); }
java
public byte[] getHash() { // digester.digest() resets the digester, so it cannot be called multiple times, // therefore we cache the hash if(hash == null) { hash = hasher.getDigester().digest(); if(hasher.getSalt() != null) { hasher.getDigester().update(hasher.getSalt()); } } return hash; }
python
def __get_queue_opts(queue=None, backend=None): ''' Get consistent opts for the queued runners ''' if queue is None: queue = __opts__.get('runner_queue', {}).get('queue') if backend is None: backend = __opts__.get('runner_queue', {}).get('backend', 'pgjsonb') return {'backend': b...
java
public ItemTransformComponent firstPerson(Matrix4f left, Matrix4f right) { this.firstPersonLeftHand = left; this.firstPersonRightHand = right; return this; }
java
public BoardingPassBuilder addAuxiliaryField(String label, String value) { Field field = new Field(label, value); this.boardingPass.addAuxiliaryField(field); return this; }
java
private CompletableFuture<Void> commitTransactions(String scope, String stream, List<Long> segments, List<UUID> transactionsToCommit) { // Chain all transaction commit futures one after the other. This will ensure that order of commit ...
java
public StrBuilder appendSeparator(final String separator, final int loopIndex) { if (separator != null && loopIndex > 0) { append(separator); } return this; }
java
private static boolean toBeIgnoredByJackson(Class<?> clazz, String field) { Annotation[] annotations = AnnotationUtils.getAnnotations(clazz); return annotations == null // ? false // : Arrays.stream(annotations) // .filter(annotation -> annotation.annotationType().equals(JsonIgnoreProperties.class))...
java
public void saveIfNotExists(T object) throws ConditionalCheckFailedException { final DynamoDBSaveExpression saveExpression = new DynamoDBSaveExpression(); for (final DynamoDBMapperFieldModel<T,Object> key : model.keys()) { saveExpression.withExpectedEntry(key.name(), new ExpectedAttributeVal...
java
@Override public void removeByC_C(long classNameId, long classPK) { for (CPFriendlyURLEntry cpFriendlyURLEntry : findByC_C(classNameId, classPK, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(cpFriendlyURLEntry); } }
java
@Deprecated public C expectBetween(int minAllowedStatements, int maxAllowedStatements, Threads threadMatcher) { return expect(SqlQueries.queriesBetween(minAllowedStatements, maxAllowedStatements).threads(threadMatcher)); }
python
def easeInOutCirc(n): """A circular tween function that accelerates, reaches the midpoint, and then decelerates. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine(...
java
public Geometry toGeometry(GoogleMapShape shape) { Geometry geometry = null; Object shapeObject = shape.getShape(); switch (shape.getGeometryType()) { case POINT: LatLng point = null; switch (shape.getShapeType()) { case LAT_LNG:...
java
private Object asList(Object value) { Class<?> componentClass = value.getClass().getComponentType(); if (componentClass.isPrimitive()) { if (componentClass.equals(int.class)) { return asIntList(value); } else if (componentClass.equals(long.class)) { ...
java
public Class getPropertyType(String propertyPath) { if (propertyPath == null) { throw new IllegalArgumentException("Propertyname may not be null"); } StringTokenizer tokenizer = new StringTokenizer(propertyPath, ".", false); return getPropertyType(tokenizer); }
java
@Override public ArtifactContainer createContainer(File cacheDir, ArtifactContainer parent, ArtifactEntry entry, Object o) { if (o instanceof Bundle) { return new BundleArchive(cacheDir, (Bundle) o, parent, entry, this); } return null; }
python
def http_request(self, path, method='GET', content=None, content_type="application/json", response_format=FMT_JSON): """ Perform an administrative HTTP request. This request is sent out to th...
python
def _prepare_for_cross_validation(self, corr, clf): """Prepare data for voxelwise cross validation. If the classifier is sklearn.svm.SVC with precomputed kernel, the kernel matrix of each voxel is computed, otherwise do nothing. Parameters ---------- corr: 3D array in s...
java
private FieldType getFieldType(byte[] data, int offset) { int fieldIndex = MPPUtility.getInt(data, offset); return FieldTypeHelper.mapTextFields(FieldTypeHelper.getInstance14(fieldIndex)); }
python
def get_cmd(self): """Returns the full command to be executed at runtime""" cmd = None if self.test_program in ('nose', 'nosetests'): cmd = "nosetests %s" % self.file_path elif self.test_program == 'django': executable = "%s/manage.py" % self.file_path ...
python
def append(self, obj): """Append an element to the end of the list. Parameters ---------- obj : KQMLObject or str If a string is passed, it is instantiated as a KQMLToken before being added to the list. """ if isinstance(obj, str): obj...
python
def get_node(self, node_id, project_id=None): """ Returns a Node instance. :param node_id: Node identifier :param project_id: Project identifier :returns: Node instance """ if project_id: # check the project_id exists project = ProjectMa...
python
def to_normal_url(cls, url): """ convert a URL from local mercurial URL schemes to "normal" URLS example:: # schemes.gh = git://github.com/ # remote_url = "gh://westurner/dotfiles" >> to_normal_url(remote_url) << 'git://github.com/westurner/dotfi...
python
def to_dict(self): """Internal state""" return dict( after=self._kwargs.get('after'), data=list(self), has_more=self._has_more, limit=self._max_results, order=self._kwargs.get('order', 'ASC'), page_size=self._page_size, ...
java
@Override public Request<ModifyInstancePlacementRequest> getDryRunRequest() { Request<ModifyInstancePlacementRequest> request = new ModifyInstancePlacementRequestMarshaller().marshall(this); request.addParameter("DryRun", Boolean.toString(true)); return request; }
java
public List<TorrentStatus> status() { torrent_status_vector v = alert.getStatus(); int size = (int) v.size(); List<TorrentStatus> l = new ArrayList<>(size); for (int i = 0; i < size; i++) { l.add(new TorrentStatus(v.get(i))); } return l; }
python
def label_to_latex(text): # pylint: disable=anomalous-backslash-in-string r"""Convert text into a latex-passable representation. This method just escapes the following reserved LaTeX characters: % \ _ ~ &, whilst trying to avoid doubly-escaping already escaped characters Parameters -------...
python
def _with_inline(func, admin_site, metadata_class, inline_class): """ Decorator for register function that adds an appropriate inline.""" def register(model_or_iterable, admin_class=None, **options): # Call the (bound) function we were given. # We have to assume it will be bound to admin_sit...
python
def append_flanking_markers(qtls_mk_file, flanking_markers): """ Append the flanking markers extracted in the process of generating the MapChart to the QTL list file. """ matrix = read_input_file(qtls_mk_file, sep=',') output = [] cnt = 0 for row in matrix: if cnt == 0: m...
java
public String getFrameData() { if (SockJsFrameType.OPEN == getType() || SockJsFrameType.HEARTBEAT == getType()) { return null; } else { return getContent().substring(1); } }
python
def process_from_splash(self): ''' Add softwares found in the DOM ''' for software in self._softwares_from_splash: plugin = self._plugins.get(software['name']) # Determine if it's a version or presence result try: additional_data = {'version': softwar...
python
def chat_meMessage(self, *, channel: str, text: str, **kwargs) -> SlackResponse: """Share a me message into a channel. Args: channel (str): The channel id. e.g. 'C1234567890' text (str): The message you'd like to share. e.g. 'Hello world' """ kwargs.update({"chan...
python
def data_and_files(self, data=True, files=True, stream=None): """Retrieve body data. Returns a two-elements tuple of a :class:`~.MultiValueDict` containing data from the request body, and data from uploaded files. If the body data is not ready, return a :class:`~asyncio.Future`...
python
def elapsed(self): """Returns the number of seconds it has been since the start until the latest entry.""" if not self.started or self._start_time is None: return 0.0 return self._timing_data[-1][0] - self._start_time
python
def replace_all_post_order(expression: Expression, rules: Iterable[ReplacementRule]) \ -> Union[Expression, Sequence[Expression]]: """Replace all occurrences of the patterns according to the replacement rules. A replacement rule consists of a *pattern*, that is matched against any subexpression of ...
python
def get_queryset(self): """ Return queryset limited to not removed entries. """ kwargs = {'model': self.model, 'using': self._db} if hasattr(self, '_hints'): kwargs['hints'] = self._hints return self._queryset_class(**kwargs).filter(is_removed=False)
python
def interval_tree(intervals): """Construct an interval tree :param intervals: list of half-open intervals encoded as value pairs *[left, right)* :assumes: intervals are lexicographically ordered ``>>> assert intervals == sorted(intervals)`` :returns: the root of the ...
java
public void resetLink(String linkName) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "resetLink", linkName); try { DestinationHandler link = linkIndex.findByName(linkName, null); checkDestinationHandlerExists( ...
python
def translate_comment(self, comment, link_resolver): """ Given a gtk-doc comment string, returns the comment translated to the desired format. """ out = u'' self.translate_tags(comment, link_resolver) ast = self.comment_to_ast(comment, link_resolver) out ...
python
def read_xml(cls, url, markup, game, players): """ read xml object :param url: contents url :param markup: markup provider :param game: MLBAM Game object :param players: MLBAM Players object :return: pitchpx.game.game.Game object """ innings = Inni...
python
def suggest(self, name, text, **kwargs): """ Add a suggestions request to the search. :arg name: name of the suggestion :arg text: text to suggest on All keyword arguments will be added to the suggestions body. For example:: s = Search() s = s.suggest('...
python
def destroyTempDir(self, tempDir): """Removes a temporary directory in the temp file dir, checking its in the temp file tree. The dir will be removed regardless of if it is empty. """ #Do basic assertions for goodness of the function assert os.path.isdir(tempDir) assert o...
python
def wait_pid(self): "Wait for the daemon, get its PID and a control-socket connection." while True: try: fp = open(self.pidfile) except IOError: time.sleep(0.1) continue try: fp.seek(0) pi...
java
@Override public final Long next() { checkState(mNext, "IAxis.next() must be called exactely once after hasNext()" + " evaluated to true."); mKey = mRTX.getNode().getDataKey(); mNext = false; return mKey; }
python
def _module_dir(handle): """Returns the directory where to cache the module.""" cache_dir = resolver.tfhub_cache_dir(use_temp=True) return resolver.create_local_module_dir( cache_dir, hashlib.sha1(handle.encode("utf8")).hexdigest())
python
def create_estimation_obj(model_obj, init_vals, mappings=None, ridge=None, constrained_pos=None, weights=None): """ Should return a model estimation object corresponding to the model...
java
public void encodeTo(QualityFormat format, byte[] buffer, int offset) { byte vo = format.getOffset(); for (int i = 0; i < data.length; ++i) buffer[offset++] = (byte) (data[i] + vo); } /** * Encodes current quality line with given offset. Common values for offset are 33 and 64. ...
python
def read_questions(self): """Reads questions section of packet""" format = '!HH' length = struct.calcsize(format) for i in range(0, self.num_questions): name = self.read_name() info = struct.unpack(format, self.data[self.offset:self.offset + le...
java
public CompletableFuture<Object> postAsync(@DelegatesTo(HttpConfig.class) final Closure closure) { return CompletableFuture.supplyAsync(() -> post(closure), getExecutor()); }
python
def joint_OT_mapping_kernel(xs, xt, mu=1, eta=0.001, kerneltype='gaussian', sigma=1, bias=False, verbose=False, verbose2=False, numItermax=100, numInnerItermax=10, stopInnerThr=1e-6, stopThr=1e-5, log=False, ...
python
def expand_rule(self, rule): "Returns all init_ptrs accessible by rule (recursive)" init_ptrs = set() def _expand_rule(rule): assert not rule.is_term, rule for r in self.rules_by_origin[rule]: init_ptr = RulePtr(r, 0) init_ptrs.add(init_pt...
java
public static FileStatus[] listStatus(FileSystem fs, Path f, int depth) throws IOException { if (null == f) { throw new IllegalArgumentException("Path cannot be null."); } if (null == fs) { throw new IllegalArgumentException("File system cannot be null."); } if (depth < 0) { ...
python
def headerLink( self, headerText, text=False): """*generate a link to a MMD header* **Key Arguments:** - ``headerText`` -- the header text (or anchor tag) - ``text`` -- the doc text to link. Default *False* **Return:** - `...
java
@Override public void attachInfo(Context context, ProviderInfo info) { super.attachInfo(context, info); // Sanity check our security if (info.exported) { throw new SecurityException("Provider must not be exported"); } if (!info.grantUriPermissions) { throw new SecurityException("Provide...
java
private void deleteResourceFromProject(CmsObject cms, CmsResource res) throws CmsException { CmsLock lock = cms.getLock(res); if (lock.isUnlocked() || lock.isLockableBy(cms.getRequestContext().getCurrentUser())) { cms.lockResourceTemporary(res); } else { cms.changeLock(r...
python
def union(input, **params): """ Union transformation :param input: :param params: :return: """ res = [] for col in input: res.extend(input[col]) return res
java
public Float getAsNullableFloat(String key) { Object value = getAsObject(key); return FloatConverter.toNullableFloat(value); }
python
def ystep(self): r"""Minimise Augmented Lagrangian with respect to :math:`\mathbf{y}`. """ AXU = self.AX + self.U Y0 = (self.rho*(self.block_sep0(AXU) - self.S)) / \ (self.W**2 + self.rho) Y1 = sp.prox_l1(self.block_sep1(AXU), (self.l...
python
def add_path(self, nodes, t=None): """Add a path at time t. Parameters ---------- nodes : iterable container A container of nodes. t : snapshot id (default=None) See Also -------- add_path, add_cycle Examples -------- ...
java
private synchronized void updateBytesWrittenMeter() { if (this.bytesWrittenMeter.isPresent()) { try { this.bytesWrittenMeter.get().mark(bytesWritten() - this.bytesWrittenMeter.get().getCount()); } catch (IOException e) { log.error("Cannot get bytesWritten for DataWriter, will not update ...
python
def _apply_scsi_controller(adapter, adapter_type, bus_sharing, key, bus_number, operation): ''' Returns a vim.vm.device.VirtualDeviceSpec object specifying to add/edit a SCSI controller adapter SCSI controller adapter name adapter_type SCSI controller ada...
python
def __check_classes(self): """ Check if any of the default classes (`Authentication`, `Configuration` and / or `Responses`) have been overwitten and if they're still valid """ # msg took from BaseAuthentication msg = ( "Sanic JWT was not initialized properly. ...
java
@Override public int getMediumInt() { byte b1 = get(); byte b2 = get(); byte b3 = get(); if (ByteOrder.BIG_ENDIAN.equals(order())) { return getMediumInt(b1, b2, b3); } else { return getMediumInt(b3, b2, b1); } }
java
public void warn(final String msg) { if (proxy.isWarnEnabled()) { if (proxy instanceof LocationAwareLogger) { ((LocationAwareLogger) proxy).log(null, FQCN, LocationAwareLogger.WARN_INT, msg, null, null); } else { proxy.warn(msg); } } ...
python
def _register_mecab_loc(location): ''' Set MeCab binary location ''' global MECAB_LOC if not os.path.isfile(location): logging.getLogger(__name__).warning("Provided mecab binary location does not exist {}".format(location)) logging.getLogger(__name__).info("Mecab binary is switched to: {}"....
java
public AccessLevel getAccess(User user, String repository, String path) { return getAccess(user.getName(), repository, path); }
python
def deprecated(func, msg='', *args, **kw): """ A family of decorators to mark deprecated functions. :param msg: the message to print the first time the deprecated function is used. Here is an example of usage: >>> @deprecated(msg='Use new_function instead') ... def old_functio...
python
def create_forwarding_script(filepath, module, func_name, *nargs, **kwargs): """Create a 'forwarding' script. A forwarding script is one that executes some arbitrary Rez function. This is used internally by Rez to dynamically create a script that uses Rez, even though the parent environment may not be ...
java
public static <P, T> PositionFactory<P, T> optional(BiConsumer<? super P, ? super T> mutator) { Validate.isInstanceOf(Mutator.class, mutator, "Cannot detect property from %s; missing %s?", mutator, THERIAN_PROPERTY_METHOD_WEAVER); final boolean optional = true; return new PositionFac...
java
protected void installNotificationWidget() { if (m_notificationWidgetInstalled) { return; } // remember current notification widget m_parentNotificationWidget = CmsNotification.get().getWidget(); // create our own notification overlay if (m_ownNotificationWid...
python
def postcmd(self, stop, line): ''' Exit cmd cleanly. ''' self.color_prompt() return Cmd.postcmd(self, stop, line)
java
public static Location of(final Latitude latitude, final Longitude longitude) { return new Location(latitude, longitude, null); }