language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def _load_single_patient_cufflinks(self, patient, filter_ok): """ Load Cufflinks gene quantification given a patient Parameters ---------- patient : Patient filter_ok : bool, optional If true, filter Cufflinks data to row with FPKM_status == "OK" Ret...
java
public boolean isInState(JComponent c) { return (c instanceof JTabbedPane && ((JTabbedPane) c).getTabPlacement() == JTabbedPane.LEFT); }
python
def parameters(self, params): """ Sets the list of search parameters to use. :param params: list of AbstractSearchParameter objects :type params: list """ array = JavaArray(jobject=JavaArray.new_instance("weka.core.setupgenerator.AbstractParameter", len(params))) ...
java
CompletableFuture<Map<UUID, Long>> getBucketOffsets(DirectSegmentAccess segment, Collection<UUID> hashes, TimeoutTimer timer) { Exceptions.checkNotClosed(this.closed.get(), this); if (hashes.isEmpty()) { // Nothing to search. return CompletableFuture.completedFuture(Collections....
java
@Override public void updateGeneratedFields(boolean performEditionChecking) throws RepositoryResourceCreationException { super.updateGeneratedFields(performEditionChecking); if (getType() == ResourceType.INSTALL) { generateAppliesToFilterInfo(); } }
java
private void drawDividerDrawable(Canvas c, RecyclerView parent) { int headersCount = 0; int footerCount = 0; int itemViewCount; FamiliarRecyclerView curFamiliarRecyclerView = null; if (parent instanceof FamiliarRecyclerView) { curFamiliarRecyclerView = (FamiliarRecyc...
python
def _populate_comptparms(self, img_array): """Instantiate and populate comptparms structure. This structure defines the image components. Parameters ---------- img_array : ndarray Image data to be written to file. """ # Only two precisions are possib...
python
def overridden_by_assumptions(*args): '''Stores what assumptions a function is overridden by as an attribute.''' args = tuple(args) def decorator(func): func.overridden_by_assumptions = args return func return decorator
java
private static MessageInfoType mapMessageInfo(MessageInfo messageInfo) { if (messageInfo == null) { return null; } MessageInfoType miType = new MessageInfoType(); miType.setMessageId(messageInfo.getMessageId()); miType.setFlowId(messageInfo.getFlowId()); miTyp...
python
def write(self, fh, deparsed=None): """Write the currently parsed RiveScript data into a file. Pass either a file name (string) or a file handle object. This uses ``deparse()`` to dump a representation of the loaded data and writes it to the destination file. If you provide your own da...
java
public static void setAttributeExhibitable(Boolean isExhibit) { final Preferences prefs = Preferences.userNodeForPackage(BusLayerConstants.class); if (prefs != null) { if (isExhibit == null) { prefs.remove("EXHIBIT_ATTRIBUTES"); //$NON-NLS-1$ } else { prefs.putBoolean("EXHIBIT_ATTRIBUTES", isExhibit.b...
java
public synchronized void prepareForReception() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "prepareForReception"); long length = prepareForTransmission(); // Allocate another WsByteBuffer to copy it all into WsByteBuffer newBuffer = createNewWsBy...
python
def choose_include_text(s, params, source_path): """Given the contents of a file and !inc[these params], return matching lines If there was a problem matching parameters, return empty list. :param s: file's text :param params: string like "start-at=foo&end-at=bar" :param source_path: path to source .md. Use...
java
public static void markPartOfProcessApplication(DeploymentUnit unit) { if(unit.getParent() != null && unit.getParent() != unit) { unit.getParent().putAttachment(PART_OF_MARKER, Boolean.TRUE); } }
python
def run(self): """Main service entrypoint. Called via Thread.start() via PantsDaemon.run().""" if not (self._watchman and self._watchman.is_alive()): raise PantsService.ServiceError('watchman is not running, bailing!') # Enable watchman for the build root. self._watchman.watch_project(self._buil...
java
public void cancel(String resourceGroupName, String workflowName, String runName) { cancelWithServiceResponseAsync(resourceGroupName, workflowName, runName).toBlocking().single().body(); }
java
private void refineMotionEstimate() { // use observations from the inlier set List<Stereo2D3D> data = new ArrayList<>(); int N = matcher.getMatchSet().size(); for( int i = 0; i < N; i++ ) { int index = matcher.getInputIndex(i); PointTrack l = candidates.get(index); LeftTrackInfo info = l.getCookie()...
java
public static String getMD5Checksum(String text) { final byte[] data = stringToBytes(text); return getChecksum(MD5, data); }
python
def all(self): r"""Returns all content in this node, regardless of whitespace or not. This includes all LaTeX needed to reconstruct the original source. >>> from TexSoup import TexSoup >>> soup = TexSoup(r''' ... \newcommand{reverseconcat}[3]{#3#2#1} ... ''') >>>...
python
def iter_find_files(directory, patterns, ignored=None): """Returns a generator that yields file paths under a *directory*, matching *patterns* using `glob`_ syntax (e.g., ``*.txt``). Also supports *ignored* patterns. Args: directory (str): Path that serves as the root of the search....
java
public JobWithJars getPlanWithJars() throws ProgramInvocationException { if (isUsingProgramEntryPoint()) { List<File> allJars = new ArrayList<File>(); allJars.add(jarFile); allJars.addAll(extractedTempLibraries); return new JobWithJars(getPlan(), allJars, userCodeClassLoader); } else { throw ...
java
public static DiscountCurveInterpolation createDiscountCurveFromDiscountFactors( String name, LocalDate referenceDate, double[] times, double[] givenDiscountFactors, boolean[] isParameter, InterpolationMethod interpolationMethod, ExtrapolationMethod extrapolationMethod, InterpolationEntity interpolationEntity)...
python
def scheduler(self): """Returns the scheduler object.""" if self._scheduler is None: self._scheduler = xenon.Scheduler.create(**self.scheduler_args) return self._scheduler
java
public Set<Long> keySet() { return new AbstractSet<Long> () { public void clear ( ) { NonBlockingHashMapLong.this.clear ( ); } public int size ( ) { return NonBlockingHashMapLong.this.size ( ); } public boolean contains( Object k ) { return NonBlockingHash...
java
public Object evaluate(String pExpressionString, Object pContext, Class pExpectedType, Map functions, String defaultPrefix) throws ELException { return evaluate(pExpressionString, ...
java
private void drawAttributedString(Graphics2D g, int x, int y, String text) { if (!ctx.getTextDecoration().isEmpty()) { AttributedString as = new AttributedString(text); as.addAttribute(TextAttribute.FONT, ctx.getFont()); if (ctx.getTextDecoration().contains(CSSPr...
java
@Override public TemporalDataModelIF<Long, Long> parseTemporalData(final File f) throws IOException { return parseData(f, "\t", true); }
java
private Collection<ByteBuf> parseJsonFrame(Channel channel, ByteBuf channelBuffer) throws IOException { sequenceNum = channelBuffer.readUnsignedInt(); LOG.trace("Received sequence number {}", sequenceNum); final int jsonLength = Ints.saturatedCast(channelBuffer.readUnsignedInt()); fina...
python
def get_cursor(source, spelling): """Obtain a cursor from a source object. This provides a convenient search mechanism to find a cursor with specific spelling within a source. The first argument can be either a TranslationUnit or Cursor instance. If the cursor is not found, None is returned. "...
java
public synchronized void refresh(ApplicationMonitorConfig config) { if (config != null && config.isDropinsMonitored()) { //ApplicationMonitorConfig prevConfig = _config.getAndSet(config); _config.set(config); // keep track of the old monitored directory to see if we need to ...
python
def qteAdjustWidgetSizes(self, handlePos: int=None): """ Adjust the widget size inside the splitter according to ``handlePos``. See ``pos`` argument in _qteSplitterMovedEvent for a more detailed explanation. If ``handlePos`` is **None**, then the widgets are assigne equal size....
python
def as_PIL(self): """Get image data in :py:mod:`PIL:PIL.Image` form. Note that if the image data is already in the correct format this is a null operation. :return: The image data as :py:mod:`PIL:PIL.Image`. :rtype: :py:mod:`PIL:PIL.Image` """ if isinstance(se...
java
private List extractModuleNames() { List modules = new ArrayList(); StringTokenizer tok = new StringTokenizer(getParamModule(), ","); while (tok.hasMoreTokens()) { String module = tok.nextToken(); modules.add(module); } return modules; }
python
def backUpDB() : """backup the current database version. automatically called by importGenome(). Returns the filename of the backup""" st = time.ctime().replace(' ', '_') fn = conf.pyGeno_RABA_DBFILE.replace('.db', '_%s-bck.db' % st) shutil.copy2(conf.pyGeno_RABA_DBFILE, fn) return fn
java
public static Optional<NameID> getNameId(Response response, SamlNameIdFormat expectedFormat) { return getNameId(response, nameId -> nameId.getFormat().equals(expectedFormat.urn())); }
java
public R call() throws ExecutionException, RetryException { long elapsed = 0; TimeUnit unit = TimeUnit.MILLISECONDS; Stopwatch watch = Stopwatch.createStarted(); for (int attempt = 1; ; attempt++) { Tried<R> target = null; if (!this.rejection.apply(target...
java
public ByteArrayQueue add(byte[] b, int off, int len) { int newLength = addLength(len); System.arraycopy(b, off, array, offset + length, len); length = newLength; return this; }
java
protected NumberBinding bindHeight() { return Bindings.divide(model().localFacade().globalFacade().application().stage().heightProperty(), 768); }
python
def _(text, *args, **kwargs): """Translate and then and format the text with ``str.format``.""" msg = _t.gettext(text) if args or kwargs: return msg.format(*args, **kwargs) else: return msg
java
public Integer delete(CMAEnvironment environment) { assertNotNull(environment.getSpaceId(), "spaceId"); assertNotNull(environment.getId(), "environmentId"); return service.delete( getVersionOrThrow(environment, "version"), environment.getSpaceId(), environment.getId() ).blocking...
python
def main(): # pragma: no cover """Main entry point.""" try: # Exit on broken pipe. signal.signal(signal.SIGPIPE, signal.SIG_DFL) except AttributeError: # SIGPIPE is not available on Windows. pass try: return _main(sys.argv, standard_out=sys....
python
def mobile_template(template): """ Mark a function as mobile-ready and pass a mobile template if MOBILE. For example:: @mobile_template('a/{mobile/}b.html') def view(template=None): ... if ``request.MOBILE=True`` the template will be `a/mobile/b.html`. if ``request.MO...
java
public static ParameterizedN1qlQuery parameterized(Statement statement, JsonArray positionalParams, N1qlParams params) { return new ParameterizedN1qlQuery(statement, positionalParams, params); }
python
def _expect_token(self, expected): """ Compares the next token in the stream to the specified token. `expected` Expected token string to match. * Raises a ``ParseError`` exception if token doesn't match `expected`. """ item = self._lex...
java
@Override public void renderTile(Graphic g, MapTile map, Tile tile, int x, int y) { final SpriteTiled sprite = map.getSheet(tile.getSheet()); sprite.setLocation(x, y); sprite.setTile(tile.getNumber()); sprite.render(g); }
python
def run_show_config(args): """Show the current configuration""" # TODO Proposal: remove the "hidden" configuration. Only show config. If # the system needs to be configured, then display information on how to # configure the system. config = copy.deepcopy(bigchaindb.config) del config['CONFIGURE...
python
def depth(self): """ Return an integer representing the number of hierarchical levels in this category collection. Returns 1 for non-hierarchical categories and 0 if no categories are present (generally meaning no series are present). """ cat = self._xChart.cat ...
java
@Override protected void doGet( final HttpServletRequest request, final HttpServletResponse response ) throws ServletException, IOException { if ( "/favicon.ico".equals( request.getRequestURI() ) ) { super.doGet( request, response ); return; } final Stri...
java
public static BaseFont createFont(String name, String encoding, boolean embedded, boolean cached, byte ttfAfm[], byte pfb[]) throws DocumentException, IOException { return createFont(name, encoding, embedded, cached, ttfAfm, pfb, false); }
python
def validate_username(self, data, value): """ Ensure the username is unique If the login is being created then simply check if the username is in the store & fail. Otherwise if the login is being updated check if the existing rid on a username match is the same as the l...
java
@Override public List<CPFriendlyURLEntry> findByG_C_C_M(long groupId, long classNameId, long classPK, boolean main, int start, int end, OrderByComparator<CPFriendlyURLEntry> orderByComparator) { return findByG_C_C_M(groupId, classNameId, classPK, main, start, end, orderByComparator, true); }
java
public String getEventType() { if (cachedEventName != null) { return cachedEventName; } Class<E> clazz = getEventClass(); try { Field field = clazz.getField("TYPE_NAME"); field.setAccessible(true); cachedEventName = (String) field.get(null)...
java
public String dialogButtonsOkCancelAdvanced( String okAttributes, String cancelAttributes, String advancedAttributes) { return dialogButtons( new int[] {BUTTON_OK, BUTTON_CANCEL, BUTTON_ADVANCED}, new String[] {okAttributes, cancelAttributes, advancedAttributes})...
java
private static String getResourceIpAddress(HttpAcceptSession acceptSession, String parameterName) { String resourceIpAddress = null; ResourceAddress resourceAddress = null; switch (parameterName) { case FORWARDED_FOR: resourceAddress = acceptSession.getRemoteAddress(); ...
java
public static final Mem byte_ptr_abs(long target, long disp, SEGMENT segmentPrefix) { return _ptr_build_abs(target, disp, segmentPrefix, SIZE_BYTE); }
java
@Override public void unregister(final Context context, final Callback<Void> callback) { new AsyncTask<Void, Void, Exception>() { @Override protected Exception doInBackground(Void... params) { try { if ((deviceToken == null) || (deviceToken.trim(...
python
def get_date(cls, name): """ Checks a string for a possible date formatted into the name. It assumes dates do not have other numbers at the front or head of the date. Currently only supports dates in 1900 and 2000. Heavily relies on datetime for error checking to see if dat...
python
def to_loops(self, commands): ''' commands : list of tuples, as output from to_tuples() method, eg: [('M', 1, 2), ('L', 3, 4), ('L', 5, 6), ('z')] Interprets the command characters at the start of each tuple to return a list of loops, where each loop is a closed list of verts...
python
def splitSong(songToSplit, start1, start2): """Split a song into two parts, one starting at start1, the other at start2""" print "start1 " + str(start1) print "start2 " + str(start2) # songs = [songToSplit[:start1+2000], songToSplit[start2-2000:]] songs = [songToSplit[:start1], songToSplit[start2:]]...
java
private String getBundleName() { if (StringUtils.isEmpty(annotation.bundle())) { final String lbundle = getClass().getPackage().getName() + "." + getConventionalName(); LOGGER.debug("Bundle: {} based on conventional name.", lbundle); return lbundle; } final String lbundle = annotation.bundle(); LOGGER...
java
public String getId() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { SibTr.entry(tc, "getId"); SibTr.exit(tc, "getId", Long.toString(_messageID)); } return ""+_messageID; }
java
@Override public void startSync(AlluxioURI ufsUri) { LOG.debug("Add {} as a sync point", ufsUri.toString()); mUfsUriList.add(ufsUri); }
python
def parse(self): """Parses the JPEG 2000 file. Raises ------ IOError The file was not JPEG 2000. """ self.length = os.path.getsize(self.filename) with open(self.filename, 'rb') as fptr: # Make sure we have a JPEG2000 file. It could be e...
java
@SuppressWarnings("unchecked") private void writeValue(Type expected, Object value, TreePruner pruner, DataWriter writer, boolean skipIfFail) throws IOException { if(value==null) { writer.valueNull(); return; } if(value instanceof CustomExportedBean) { wr...
python
def cancel_subscribe(self, access_token, show_id): """doc: ?? """ url = 'https://openapi.youku.com/v2/users/subscribe/cancel.json' params = { 'client_id': self.client_id, 'access_token': access_token, 'show_id': show_id } r = requests.p...
python
def unicodestr(s, encoding='utf-8', fallback='iso-8859-1'): """Convert a string to unicode if it isn't already.""" if isinstance(s, unicode): return s try: return s.decode(encoding) except UnicodeError: return s.decode(fallback)
java
private void handleRename(final TSDB tsdb, final HttpQuery query) { // only accept GET and POST if (query.method() != HttpMethod.GET && query.method() != HttpMethod.POST) { throw new BadRequestException(HttpResponseStatus.METHOD_NOT_ALLOWED, "Method not allowed", "The HTTP method[" + query.metho...
python
def opt_with_frequency_flattener(cls, qchem_command, multimode="openmp", input_file="mol.qin", output_file="mol.qout", qclog_file="mol....
python
def sync(self): """Commit deferred writes to file.""" for key_hash, obj in six.iteritems(self._cache): # Objects are checked for expiration in __getitem__, # but we can check here to avoid unnecessary writes. if not obj.has_expired(): file_path = self....
python
def _set_show_fabric_trunk_info(self, v, load=False): """ Setter method for show_fabric_trunk_info, mapped from YANG variable /brocade_fabric_service_rpc/show_fabric_trunk_info (rpc) If this variable is read-only (config: false) in the source YANG file, then _set_show_fabric_trunk_info is considered as ...
java
public int getTimeoutValueInSSLClosingHandshake() { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "timeoutValueInSSLClosingHandshake : " + this.timeoutValueInSSLClosingHandshake); } return this.timeoutValueInSSLClosingHandshake; }
python
def run(self, host: str = '0.0.0.0', port: int = 8080): """ Start sirbot Configure sirbot and start the aiohttp.web.Application Args: host (str): host port (int): port """ self._loop.run_until_complete(self._configure_plugins()) web.run_a...
python
def dehtml(text): '''Remove HTML tag in input text and format the texts accordingly. ''' # added by BoPeng to handle html output from kernel # # Do not understand why, but I cannot define the class outside of the # function. try: # python 2 from HTMLParser import HTMLParser ...
python
def handle_request(self, request_text=None): """Handle a single XML-RPC request passed through a CGI post method. If no XML data is given then it is read from stdin. The resulting XML-RPC response is printed to stdout along with the correct HTTP headers. """ if request_...
python
def AddExtraShapes(extra_shapes_txt, graph): """ Add extra shapes into our input set by parsing them out of a GTFS-formatted shapes.txt file. Useful for manually adding lines to a shape file, since it's a pain to edit .shp files. """ print("Adding extra shapes from %s" % extra_shapes_txt) try: tmpdi...
java
protected Float getExpressionResolution(MediaExpression e) { if (e.size() == 1) //the length requires exactly one value { Term<?> term = e.get(0); if (term instanceof TermResolution) return dpiResolution((TermResolution) term); else ...
python
def xml_records(filename): """ If the second return value is not None, then it is an Exception encountered during parsing. The first return value will be the XML string. @type filename str @rtype: generator of (etree.Element or str), (None or Exception) """ with Evtx(filename) as e...
java
public static int lastIndexOf(final String value, final String needle) { validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER); return lastIndexOf(value, needle, value.length(), true); }
java
void setBaseValues(CatalogMap<? extends CatalogType> parentMap, String name) { if (name == null) { throw new CatalogException("Null value where it shouldn't be."); } m_parentMap = parentMap; m_typename = name; }
python
def list(gandi, id, limit): """ List SSH keys. """ options = { 'items_per_page': limit, } output_keys = ['name', 'fingerprint'] if id: output_keys.append('id') result = gandi.sshkey.list(options) for num, sshkey in enumerate(result): if num: gandi.separ...
python
def initialize(self, id=None, title=None, namespace=None, redirect=None, restrictions=None): self.id = none_or(id, int) """ Page ID : `int` """ self.title = none_or(title, str) """ Page title (namespace excluded) : `str` """ se...
java
public net.minidev.ovh.api.debt.entry.OvhAssociatedObject bill_billId_debt_operation_operationId_associatedObject_GET(String billId, Long operationId) throws IOException { String qPath = "/me/bill/{billId}/debt/operation/{operationId}/associatedObject"; StringBuilder sb = path(qPath, billId, operationId); String ...
java
@Override public boolean add(final E element) { if (null == element) { throw new NullPointerException("Attempted to add null object to queue"); } if (isAtFullCapacity()) { remove(); } elements[end++] = element; if (end >= maxElements) { ...
python
def __error_middleware(self, res, res_json): """ Middleware that raises an exception when HTTP statuscode is an error code. """ if(res.status_code in [400, 401, 402, 403, 404, 405, 406, 409]): err_dict = res_json.get('error', {}) raise UpCloudAPIError(error_code=e...
python
def changed(self, *value): """Checks whether the value has changed since the last call.""" if self._last_checked_value != value: self._last_checked_value = value return True return False
java
public int getRawFieldData(Convert field) { String strKey = this.getFullKey(field.getFieldName()); Class<?> classData = field.getField().getDataClass(); Object objValue = this.getMessage().getNative(strKey); try { objValue = DataConverters.convertObjectToDatatype(objValue...
java
public static String substituteSiteTitleStatic(String title, Locale locale) { if (title.equals(CmsSiteManagerImpl.SHARED_FOLDER_TITLE)) { return Messages.get().getBundle(locale).key(Messages.GUI_SHARED_TITLE_0); } return title; }
python
def at(self, timestamp): """ Force the create date of an object to be at a certain time; This method can be invoked only on a freshly created Versionable object. It must not have been cloned yet. Raises a SuspiciousOperation exception, otherwise. :param timestamp: a datet...
python
def add(self, command): # type: (BaseCommand) -> Application """ Adds a command object. """ self.add_command(command.config) command.set_application(self) return self
python
def _stmt_graph_annotate_edges(self, edges_to_annotate, **new_labels): """ Add new annotations to edges in the statement dependence graph. :param list edges_to_annotate: A list of edges to annotate. :param new_labels: New labels to be added to those edges. :returns: None ...
python
def region(self, bounds): """Set region of the screen area Args: bounds: Bounds object Returns: A new AndroidDevice object Raises: TypeError """ if not isinstance(bounds, Bounds): raise TypeError("region param bounds must ...
python
def save_user(self, request, sociallogin, form=None): """ Saves a newly signed up social login. In case of auto-signup, the signup form is not available. """ u = sociallogin.user u.set_unusable_password() if form: get_account_adapter().save_user(reques...
java
public ByteArraySegment serialize(T object) throws IOException { val result = new EnhancedByteArrayOutputStream(); serialize(result, object); return result.getData(); }
java
public static Atom[] duplicateCA2(Atom[] ca2) { // we don't want to rotate input atoms, do we? Atom[] ca2clone = new Atom[ca2.length * 2]; int pos = 0; Chain c = null; String prevChainId = ""; for (Atom a : ca2) { Group g = (Group) a.getGroup().clone(); // works because each group // has only a sing...
python
def _storeConfig(self, config, configPath): """ Writes the config to the configPath. :param config a dict of config. :param configPath the path to the file to write to, intermediate dirs will be created as necessary. """ self.logger.info("Writing to " + str(configPath)) ...
java
public static State jsonObjectToState(JsonObject jsonObject, String... excludeKeys) { State state = new State(); List<String> excludeKeysList = excludeKeys == null ? Lists.<String>newArrayList() : Arrays.asList(excludeKeys); for (Map.Entry<String, JsonElement> jsonObjectEntry : jsonObject.entrySet()) { ...
java
@Command(name = "QueryWizardDevProperty", inTypeDesc = "Class name", outTypeDesc = "Device property list (name - description and default value)") public String[] queryDevProp(final String className) { xlogger.entry(); final List<String> names = new ArrayList<String>(); for (final DeviceClass...
java
@Override public void handleRequest(final Request request) { super.handleRequest(request); String targ = request.getParameter(Environment.TARGET_ID); boolean contentReqested = (targ != null && targ.equals(getTargetId())); if (contentReqested && request.getParameter(POSTER_REQUEST_PARAM_KEY) != null) { ha...
java
@Override public int getStorageStrategy() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "getStorageStrategy"); int storageStrat = getMessageItem().getStorageStrategy(); // It is possible that this reference has a lesser storage strategy ...
python
def __taint_move(self, instr): """Taint registers move instruction. """ # Get taint information. op0_taint = self.get_operand_taint(instr.operands[0]) # Propagate taint. self.set_operand_taint(instr.operands[2], op0_taint)