language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
void resetRows(int i, int marking) { for (int j = (i * mCols); j < data.length; j++) if (data[j] == marking) data[j] = 1; }
java
public long[] extractULongArray(final DeviceData deviceData) { final int[] argout = DevVarULongArrayHelper.extract(deviceData.getAny()); final long[] val = new long[argout.length]; long mask = 0x7fffffff; mask += (long) 1 << 31; for (int i = 0 ; i<argout.length ; i++) { ...
java
private String gotExtractedValue(String string) { if (!isEmpty(value_extract_regex)) { Pattern pattern = Pattern.compile(value_extract_regex); Matcher ma = pattern.matcher(string); String result = ""; while (ma.find()) { result += ma.group(0); ...
java
static String sourceFormForAnnotation(AnnotationMirror annotationMirror) { StringBuilder sb = new StringBuilder(); new AnnotationSourceFormVisitor().visitAnnotation(annotationMirror, sb); return sb.toString(); }
java
protected void addNeighborToOrdering(TrustGraphNodeId neighbor) { int position = rng.nextInt(orderedNeighbors.size()+1); if (position == orderedNeighbors.size()) { orderedNeighbors.add(neighbor); } else { orderedNeighbors.add(position, neighbor); ...
python
def user_data_dir(self): """Return ``user_data_dir``.""" directory = appdirs.user_data_dir(self.appname, self.appauthor, version=self.version, roaming=self.roaming) if self.create: self._ensure_directory_exists(directory) return directory
python
def pass_obj(f): """Similar to :func:`pass_context`, but only pass the object on the context onwards (:attr:`Context.obj`). This is useful if that object represents the state of a nested system. """ def new_func(*args, **kwargs): return f(get_current_context().obj, *args, **kwargs) retu...
java
public static String getCDIAppName(BundleContext bundleContext) { String appName = null; if (FrameworkState.isValid()) { // Get the CDIService CDIService cdiService = getCDIService(bundleContext); if (cdiService != null) { appName = cdiService.getCurre...
python
def ph_basename(self, ph_type): """ Return the base name for a placeholder of *ph_type* in this shape collection. There is some variance between slide types, for example a notes slide uses a different name for the body placeholder, so this method can be overriden by subclasses. ...
java
public Any insert(long data) throws DevFailed { Any out_any = alloc_any(); out_any.insert_longlong(data); return out_any; }
python
def exception(self, e): """Log an error messsage. :param e: Exception to log. """ self.logged_exception(e) self.logger.exception(e)
python
def percentile_doy(arr, window=5, per=.1): """Percentile value for each day of the year Return the climatological percentile over a moving window around each day of the year. Parameters ---------- arr : xarray.DataArray Input data. window : int Number of days around each day of the...
python
def get_delivery_timeline_data(self, project, id, revision=None, start_date=None, end_date=None): """GetDeliveryTimelineData. Get Delivery View Data :param str project: Project ID or project name :param str id: Identifier for delivery view :param int revision: Revision of the pla...
java
public void executeBatchStmt(boolean mustExecuteOnMaster, Results results, final List<String> queries) throws SQLException { cmdPrologue(); if (this.options.rewriteBatchedStatements) { //check that queries are rewritable boolean canAggregateSemiColumn = true; for (String query : q...
java
public String convertIfcReinforcingBarTypeEnumToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); }
python
def source(script): """Emulates 'source' command in bash :param script: (str) Full path to the script to source :return: Updated environment :raises CommandError """ log = logging.getLogger(mod_logger + '.source') if not isinstance(script, basestring): msg = 'script argument must be...
python
async def _query_validator(self, request_type, response_proto, payload, error_traps=None): """Sends a request to the validator and parses the response. """ LOGGER.debug( 'Sending %s request to validator', self._get_type_name(request_type)) ...
python
def get_version_from_tag(tag_name: str) -> Optional[str]: """Get git hash from tag :param tag_name: Name of the git tag (i.e. 'v1.0.0') :return: sha1 hash of the commit """ debug('get_version_from_tag({})'.format(tag_name)) check_repo() for i in repo.tags: if i.name == tag_name: ...
java
public Serializable parseConfig (File source) throws IOException, SAXException { Digester digester = new Digester(); Serializable config = createConfigObject(); addRules(digester); digester.push(config); digester.parse(new FileInputStream(source)); return conf...
python
def translate(ra, dec, r, theta): """ Translate a given point a distance r in the (initial) direction theta, along a great circle. Parameters ---------- ra, dec : float The initial point of interest (degrees). r, theta : float The distance and initial direction to translate (d...
java
@NonNull public RequestCreator load(@Nullable File file) { if (file == null) { return new RequestCreator(this, null, 0); } return load(Uri.fromFile(file)); }
python
def getkeypress(self): u'''Return next key press event from the queue, ignoring others.''' ck = System.ConsoleKey while 1: e = System.Console.ReadKey(True) if e.Key == System.ConsoleKey.PageDown: #PageDown self.scroll_window(12) elif e.K...
java
@Override public void doExceptionCaughtListeners(final long sessionId, final Throwable cause) { runManagementTask(new Runnable() { @Override public void run() { try { // The particular management listeners change on strategy, so get them here. ...
java
private void processFilesIntoServers() throws LifecycleException { // Shutdown the outputwriters and clear the current server list - this gives us a clean // start when re-reading the json config files try { this.stopWriterAndClearMasterServerList(); } catch (Exception e) { log.error("Error while clearing...
python
def get_portchannel_info_by_intf_output_lacp_interface_type(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_portchannel_info_by_intf = ET.Element("get_portchannel_info_by_intf") config = get_portchannel_info_by_intf output = ET.SubElement(get...
java
@Override public void send(Event event) { if (!closed) { executorService.execute(new EventSubmitter(event, MDC.getCopyOfContextMap())); } }
python
def get_site_packages_dir(self, arch=None): '''Returns the location of site-packages in the python-install build dir. ''' if self.python_recipe.name == 'python2legacy': return join(self.get_python_install_dir(), 'lib', 'python2.7', 'site-packages') ...
java
public synchronized boolean installPlugin(String id, String version) throws PluginException { // Download to temporary location Path downloaded = downloadPlugin(id, version); Path pluginsRoot = pluginManager.getPluginsRoot(); Path file = pluginsRoot.resolve(downloaded.getFileName()); ...
python
def _skySub(imageSet,paramDict,saveFile=False): """ subtract the sky from all the chips in the imagefile that imageSet represents imageSet is a single imageObject reference paramDict should be the subset from an actual config object if saveFile=True, then images that have been sky subtracted are sa...
python
def load_dwg(file_obj, **kwargs): """ Load DWG files by converting them to DXF files using TeighaFileConverter. Parameters ------------- file_obj : file- like object Returns ------------- loaded : dict kwargs for a Path2D constructor """ # read the DWG data into a b...
java
public static void copyTemplates(AbstractWisdomMojo mojo, MavenResourcesFiltering filtering) throws IOException { File in = new File(mojo.basedir, Constants.TEMPLATES_SRC_DIR); if (!in.exists()) { return; } File out = new File(mojo.getWisdomRootDirectory(), Constants.TEMPLATE...
java
@SuppressWarnings("unchecked") public Class<T> getClassType() throws ClassNotFoundException { Type clsType = getType(); if (getType() instanceof ParameterizedType) { return (Class<T>) ((ParameterizedType) clsType).getRawType(); } else { return (Class<T>) Class.forNam...
java
public static GridPanel getInstanceByTabPanel(TabPanel tabPanel, String searchColumnId) { GridPanel gridPanel = new GridPanel(); WebLocator container = tabPanel.getPathBuilder().getContainer(); gridPanel.setContainer(container); tabPanel.setContainer(null); // hack to have path without ...
java
public void applyAndJournal(Supplier<JournalContext> context, DeleteFileEntry entry) { // Unlike most entries, the delete file entry must be applied *before* making the in-memory // change. This is because delete file and create file are performed with only a read lock on // the parent directory. As soon as...
python
def get_random_line(self): """ Get random line from another document for nextSentence task. :return: str, content of one line """ # Similar to original tf repo: This outer loop should rarely go for more than one iteration for large # corpora. However, just to be careful, ...
java
public void restoreAttributes() { String attrName = getScopedName( STORED_ATTRS_ATTR ); Map savedAttrs = ( Map ) getSession().getAttribute( attrName ); if ( savedAttrs != null ) { setAttributeMap( savedAttrs ); } }
java
private boolean continueGeneratingThresholds(double limitWorkload, double workload, Solution sol, QualityInformation requirements, SuitableOptions cloudCharacteristics, boolean existModulesToScaleOut) { // Stop if the maximum number of scalings for every module has been // reached. // Stop al...
python
def normalize_dates(): """Experiment to make sense of TLG dates. TODO: start here, parse everything with pass """ _dict = get_date_author() for tlg_date in _dict: date = {} if tlg_date == 'Varia': #give a homer-to-byz date for 'varia' pass elif tlg_dat...
python
def scv_link(scv_sig, rcv_trip): ''' Creates links between SCV based on their pathonicty/significance calls # GENO:0000840 - GENO:0000840 --> is_equilavent_to SEPIO:0000098 # GENO:0000841 - GENO:0000841 --> is_equilavent_to SEPIO:0000098 # GENO:0000843 - GENO:0000843 --> is_equilavent_to SEPIO:0000...
python
def temp_fail_retry(error, fun, *args): """Retry to execute function, ignoring EINTR error (interruptions)""" while 1: try: return fun(*args) except error as e: eintr = errno.WSAEINTR if os.name == 'nt' else errno.EINTR if e.args[0] == eintr: ...
python
def beta_confidence_intervals(ci_X, ntrials, ci=0.95): """ Compute confidence intervals of beta distributions. Parameters ---------- ci_X : numpy.array Computed confidence interval estimate from `ntrials` experiments ntrials : int The number of trials that were run. ci : flo...
java
public static URI urlToURI(URL url) { try { return url.toURI(); } catch (URISyntaxException e) { throw LOG.cannotConvertUrlToUri(url, e); } }
python
def _create_action(factory_self, action_model, resource_name, service_context, is_load=False): """ Creates a new method which makes a request to the underlying AWS service. """ # Create the action in in this closure but before the ``do_action`` # me...
python
def parse_tstv_by_count(self): """ Create the HTML for the TsTv by alternative allele count linegraph plot. """ self.vcftools_tstv_by_count = dict() for f in self.find_log_files('vcftools/tstv_by_count', filehandles=True): d = {} for line in f['f'].readlines()[1:]: # don...
python
def enqueue_zonefile(self, zonefile_hash, block_height): """ Called when we discover a zone file. Queues up a request to reprocess this name's zone files' subdomains. zonefile_hash is the hash of the zonefile. block_height is the minimium block height at which this zone file occurs. ...
python
def write(self, img, start=0, **keys): """ Write the image into this HDU If data already exist in this HDU, they will be overwritten. If the image to write is larger than the image on disk, or if the start position is such that the write would extend beyond the existing ...
java
public boolean add(T item) { ListNode<T> node = new ListNode<>(item); synchronized (this.lock) { if (this.tail == null) { // List is currently empty. this.head = node; } else { if (item.getSequenceNumber() <= this.tail.item.getSeque...
python
def trigger(self, event, filter=None, update=None, documents=None, ids=None, replacements=None): """ Trigger the after_save hook on documents, if present. """ if not self.has_trigger(event): return if documents is not None: pass elif ids is not None: ...
python
def export_obo(self, path_to_export_file, name_of_ontology="uniprot", taxids=None): """ export complete database to OBO (http://www.obofoundry.org/) file :param path_to_export_file: path to export file :param taxids: NCBI taxonomy identifiers to export (optional) """ fd...
java
public DescribeSuggestersResult withSuggesters(SuggesterStatus... suggesters) { if (this.suggesters == null) { setSuggesters(new com.amazonaws.internal.SdkInternalList<SuggesterStatus>(suggesters.length)); } for (SuggesterStatus ele : suggesters) { this.suggesters.add(ele...
python
def applications(self): """ Access the applications :returns: twilio.rest.api.v2010.account.application.ApplicationList :rtype: twilio.rest.api.v2010.account.application.ApplicationList """ if self._applications is None: self._applications = ApplicationList(s...
java
private void checkNotParsing (String type, String name) throws SAXNotSupportedException { if (parsing) { throw new SAXNotSupportedException("Cannot change " + type + ' ' + name + " while parsing"); } }
java
@Override public void addListener(IDatabaseListener listener) { if (!listeners.contains(listener)) { listeners.add(listener); } }
python
def start_auth(self, context, internal_request, get_state=stateID): """ See super class method satosa.backends.base#start_auth :param get_state: Generates a state to be used in the authentication call. :type get_state: Callable[[str, bytes], str] :type context: satosa.context.Co...
java
@Override protected OneWiki getNewSource(final String _name, final Instance _instance) { return new OneWiki(_name, _instance); }
python
def datafind_connection(server=None): """ Return a connection to the datafind server Parameters ----------- server : {SERVER:PORT, string}, optional A string representation of the server and port. The port may be ommitted. Returns -------- connection The open connecti...
python
def value_occurence(s): """Count the number of times each value occurs. This function returns the counts for each row, in contrast with `pandas.value_counts <http://pandas.pydata.org/pandas- docs/stable/generated/pandas.Series.value_counts.html>`_. Returns ------- pandas.Series A S...
python
def parse(self, template): """ Parse a template string starting at some index. This method uses the current tag delimiter. Arguments: template: a unicode string that is the template to parse. index: the index at which to start parsing. Returns: ...
python
def _login(self): '''Login to the SMTP server specified at instantiation Returns an authenticated SMTP instance. ''' server, port, mode, debug = self.connection_details if mode == 'SSL': smtp_class = smtplib.SMTP_SSL else: smtp_class = smtplib.SM...
python
def change_password(self, id_user, user_current_password, password): """Change password of User from by the identifier. :param id_user: Identifier of the User. Integer value and greater than zero. :param user_current_password: Senha atual do usuário. :param password: Nova Senha do usuár...
java
public static int writeAsciiString(byte[] array, int startPos, String attribute) { Preconditions.checkArgument(isAsciiString(attribute)); if (attribute.length()==0) { array[startPos++] = (byte)0x80; } else { for (int i = 0; i < attribute.length(); i++) { i...
java
private void handleDeprecatedAnnotations(List<JCAnnotation> annotations, Symbol sym) { for (List<JCAnnotation> al = annotations; !al.isEmpty(); al = al.tail) { JCAnnotation a = al.head; if (a.annotationType.type == syms.deprecatedType) { sym.flags_field |= (Flags.DEPRECAT...
java
@Nullable public static String findContentText(final Node rootNode, final XPath xPath, final String expression) { final Node node = findNode(rootNode, xPath, expression); if (node == null) { return null; } return node.getTextContent(); }
python
def find_extensions(self, tag=None, namespace=None): """Searches extension elements for child nodes with the desired name. Returns a list of extension elements within this object whose tag and/or namespace match those passed in. To find all extensions in a particular namespace, specify ...
python
def temp_path(): """Allow the ability to set os.environ temporarily""" path = [p for p in sys.path] try: yield finally: sys.path = [p for p in path]
java
public static String decapitalize(String text) { if (isNullOrEmpty(text)) { return text; } char chars[] = text.toCharArray(); chars[0] = Character.toLowerCase(chars[0]); return new String(chars); }
python
def fromMessage(cls, message): """ @param message: The associate request message @type message: openid.message.Message @returntype: L{DiffieHellmanSHA1ServerSession} @raises ProtocolError: When parameters required to establish the session are missing. """ ...
python
def run_migrations_online(): """ Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ connectable = context.config.attributes.get("connection", None) if connectable is None: options = context.config.get_secti...
python
def __create_url_node_for_content(self, content, content_type, url=None, modification_time=None): """ Creates the required <url> node for the sitemap xml. :param content: the content class to handle :type content: pelican.contents.Content | None :param content_type: the type of t...
java
private void writeElements(SerIterator itemIterator) throws IOException { if (itemIterator.metaTypeRequired()) { output.writeObjectStart(); output.writeObjectKeyValue(META, itemIterator.metaTypeName()); output.writeObjectKey(VALUE); } if (itemIterator.category...
java
public void close() { if (rtpChannel != null) { if (rtpChannel.isConnected()) { try { rtpChannel.disconnect(); } catch (IOException e) { logger.error(e); } try { rtpChannel.socket().close(); rtpChannel.close(); } catch (IOException e) { logger.error(e); } } } ...
python
def __demodulate_data(self, data): """ Demodulates received IQ data and adds demodulated bits to messages :param data: :return: """ if len(data) == 0: return power_spectrum = data.real ** 2 + data.imag ** 2 is_above_noise = np.sqrt(np.mean(pow...
java
public String getComment(int index) { if (comments == null || index < 0 || index >= comments.size()) { throw new IllegalArgumentException("Not a valid comment index: " + index); } return (String)comments.get(index); }
python
def _create_request(self, messages): """Create a formatted request to zabbix from a list of messages. :type messages: list :param messages: List of zabbix messages :rtype: list :return: Formatted zabbix request """ msg = ','.join(messages) request = '{{...
java
private Charset guessEncoding() { // if the file has a Byte Order Marker, we can assume the file is in UTF-xx // otherwise, the file would not be human readable if (hasUTF8Bom()) return Charset.forName("UTF-8"); if (hasUTF16LEBom()) return Charset.forName("UTF-16L...
python
def kmeans(phate_op, k=8, random_state=None): """KMeans on the PHATE potential Clustering on the PHATE operator as introduced in Moon et al. This is similar to spectral clustering. Parameters ---------- phate_op : phate.PHATE Fitted PHATE operator k : int, optional (default: 8) ...
python
def main(argv=None, directory=None): """ Main entry point for the tool, used by setup.py Returns a value that can be passed into exit() specifying the exit code. 1 is an error 0 is successful run """ logging.basicConfig(format='%(message)s') argv = argv or sys.argv arg_dict = pa...
java
protected static File createTemporaryFile(@Nonnull final File file) { Check.notNull(file, "file"); final File tempFile = new File(file.getParent(), file.getName() + ".temp"); // remove orphaned temporary file deleteFile(tempFile); return tempFile; }
java
public JSONWriter with(TreeCodec tc) { if (_treeCodec == tc) { return this; } return _with(_features, _writerLocator, tc); }
java
@Override JSType resolveInternal(ErrorReporter reporter) { if (!getReferencedType().isUnknownType()) { // In some cases (e.g. typeof(ns) when the actual type is just a literal object), a NamedType // is created solely for the purpose of naming an already-known type. When that happens, // there's...
java
public void clear(String what) { if (what.equals("blockers")) blockers.clear(); else if (what.equals("datasets")) datasets.clear(); else if (what.equals("learners")) learners.clear(); else if (what.equals("all")) { clear("blockers"); clear("datasets"); clear("learners"); } else { System.out.println...
java
public static <T> List<T> queryColumn( String poolName, String sql, String columnName, Class<T> columnType, Object[] params) throws YankSQLException { List<T> returnList = null; try { ColumnListHandler<T> resultSetHandler; if (columnType.equals(Integer.class)) { resultSetHandle...
python
def setup_sfr_obs(self): """setup sfr ASCII observations""" if not self.sfr_obs: return if self.m.sfr is None: self.logger.lraise("no sfr package found...") org_sfr_out_file = os.path.join(self.org_model_ws,"{0}.sfr.out".format(self.m.name)) if not os.pat...
python
def gradient(self): """Gradient operator of the functional. The gradient is not defined in points where one or more components are less than or equal to 0. """ functional = self class KLCrossEntropyGradient(Operator): """The gradient operator of this functi...
java
private void parseAttribute(final Attributes atts) { URI target = toURI(atts.getValue(ATTRIBUTE_NAME_COPY_TO)); if (target == null) { return; } final String attrScope = atts.getValue(ATTRIBUTE_NAME_SCOPE); // external resource is filtered here. if (ATTR_SCOPE...
java
public static Document stringToXml(String string) throws Exception { if (builder == null) { throw new Exception("DocumentBuilder is null."); } return builder.parse(new InputSource(new ByteArrayInputStream(string.getBytes("UTF-8")))); }
java
public synchronized @NonNull T set(T object) { if (this.object != null) { throw new IllegalStateException("Already initialized"); } this.object = object; return object; }
python
def BuildTemplate(self, context=None, output=None, fleetspeak_service_config=None): """Find template builder and call it.""" context = context or [] context.append("Arch:%s" % self.GetArch()) # Platform context has common platform settings, Tar...
python
def parse_message(cls, message): """ Parses a message received from the Pebble. Uses Pebble Protocol framing to figure out what sort of packet it is. If the packet is registered (has been defined and imported), returns the deserialised packet, which will not necessarily be the same class...
java
protected boolean isInvalidateParent(String xpath) { if (!CmsXmlUtils.isDeepXpath(xpath)) { return false; } Boolean isInvalidateParent = null; // look up the default from the configured mappings isInvalidateParent = m_relationChecks.get(xpath); if (isInvalida...
python
def str_pad(arr, width, side='left', fillchar=' '): """ Pad strings in the Series/Index up to width. Parameters ---------- width : int Minimum width of resulting string; additional characters will be filled with character defined in `fillchar`. side : {'left', 'right', 'both'}, ...
python
def _write(self, session, openFile, replaceParamFile): """ Replace Val File Write to File Method """ # Write lines for line in self.lines: openFile.write(line.contents)
python
def raw_corpus_length_ratio(hypotheses: Iterable[str], references: Iterable[str]) -> float: """ Simple wrapper around length ratio implementation. :param hypotheses: Hypotheses stream. :param references: Reference stream. :return: Length ratio score as float. """ ratios = [len(h.split())/le...
python
def assert_child_key_has_value(self, parent, child, caller): """Assert that context contains key that has child which has a value. Args: parent: parent key child: validate this sub-key of parent exists AND isn't None. caller: string. calling function name - this used...
java
public void setControlledPanel (final JComponent panel) { panel.addHierarchyListener(new HierarchyListener() { public void hierarchyChanged (HierarchyEvent e) { boolean nowShowing = panel.isDisplayable(); //System.err.println("Controller." + Controller.this + ...
java
@Override public Object getSession(ServletRequest request, ServletResponse response, SessionAffinityContext affinityContext, boolean create) { /* * Check to see if the request provides a JSESSIONID cookie */ String sessionID = _sam.getInUseSessionID(request, affinityContext); ...
python
def _le_butt(self, annot, p1, p2, lr): """Make stream commands for butt line end symbol. "lr" denotes left (False) or right point. """ m, im, L, R, w, scol, fcol, opacity = self._le_annot_parms(annot, p1, p2) shift = 3 d = shift * max(1, w) M = R if lr else L top ...
python
def _get_mpi_info(self): """get basic MPI info Returns ------- comm : Intracomm Returns MPI communication group rank : integer Returns the rank of this process size : integer Returns total number of processes """ ra...
java
public static MultiMessage decode(String encodedMessages, TempFileContext tempFileContext) throws IOException { if(encodedMessages.isEmpty()) return EMPTY_MULTI_MESSAGE; int pos = encodedMessages.indexOf(DELIMITER); if(pos == -1) throw new IllegalArgumentException("Delimiter not found"); final int size = Integ...
java
public static final Function<Short,Boolean> isNull() { return (Function<Short,Boolean>)((Function)FnObject.isNull()); }