language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
protected void saveInternal(XMLStreamWriter stream) throws XMLStreamException { if (namespace != null) { stream.writeStartElement(prefix, namespace, name); } else { stream.writeStartElement(name); } for (Map.Entry<XAttributeName, String> a : attributes.entrySet())...
java
public VariableRef[] getOutOfScopeVariableRefs() { Scope parent; if ((parent = getParent()) == null) { return new VariableRef[0]; } Collection<VariableRef> allRefs = new ArrayList<VariableRef>(); fillVariableRefs(allRefs, this); Collection<VariableRef> refs ...
python
def pop(self, identifier, default=None): """Pop a node of the AttrTree using its path string. Args: identifier: Path string of the node to return default: Value to return if no node is found Returns: The node that was removed from the AttrTree """ ...
java
@Nonnull public PLTableRow addAndReturnRow (@Nonnull final Iterable <? extends PLTableCell> aCells) { return addAndReturnRow (aCells, m_aRows.getDefaultHeight ()); }
java
public final void mapEntry() throws RecognitionException { try { // src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:574:5: ( expression COLON expression ) // src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:574:7: expression COLON expression { pushFollow(FOLLOW_expression_in_map...
python
def decode_pubkey_hex(pubkey_hex): """ Decode a public key for ecdsa verification """ if not isinstance(pubkey_hex, (str, unicode)): raise ValueError("public key is not a string") pubk = keylib.key_formatting.decompress(str(pubkey_hex)) assert len(pubk) == 130 pubk_raw = pubk[2:] ...
java
void optimizeTransitions() { HashMap<DFAState<T>,RangeSet> hml = new HashMap<>(); for (Transition<DFAState<T>> t : transitions.values()) { RangeSet rs = hml.get(t.getTo()); if (rs == null) { rs = new RangeSet(); hml...
python
def apply_and_save(self): """Apply replaced words and patches, and save setup.py file.""" patches = self.patches content = None with open(self.IN_PATH) as f_in: # As setup.py.in file size is 2.4 KByte. # it's fine to read entire content. content = f_i...
python
def add_default_args(parser, version=None, include=None): ''' Add default arguments to a parser. These are: - config: argument for specifying a configuration file. - user: argument for specifying a user. - dry-run: option for running without side effects. - verbose: option for ru...
java
public Node clearAttributes() { Iterator<Attribute> it = attributes().iterator(); while (it.hasNext()) { it.next(); it.remove(); } return this; }
java
public void setNoteText(java.util.Collection<StringFilter> noteText) { if (noteText == null) { this.noteText = null; return; } this.noteText = new java.util.ArrayList<StringFilter>(noteText); }
python
def parse_pictures(self, picture_page): """Parses the DOM and returns character pictures attributes. :type picture_page: :class:`bs4.BeautifulSoup` :param picture_page: MAL character pictures page's DOM :rtype: dict :return: character pictures attributes. """ character_info = self.parse_s...
java
private void addSmallIcon(RemoteViews notificationView) { notificationView.setInt(R.id.simple_sound_cloud_notification_icon, "setBackgroundResource", mNotificationConfig.getNotificationIconBackground()); notificationView.setImageViewResource(R.id.simple_sound_cloud_notification_icon, ...
python
def _read_temp(data): ''' Return what would be written to disk ''' tout = StringIO() tout.write(data) tout.seek(0) output = tout.readlines() tout.close() return output
python
def ParseFileEntryMetadata(self, parser_mediator, file_entry): """Parses the file entry metadata e.g. file system data. Args: parser_mediator (ParserMediator): parser mediator. file_entry (dfvfs.FileEntry): file entry. """ if self._filestat_parser: self._ParseFileEntryWithParser( ...
java
private List<String> parseEnumData(File annotationCacheCopy, String valueDelimiter, long characterOffset) throws IOException { List<String> enumData = new ArrayList<String>(); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(anno...
python
def feature_importance(self, importance_type='split', iteration=None): """Get feature importances. Parameters ---------- importance_type : string, optional (default="split") How the importance is calculated. If "split", result contains numbers of times the featur...
java
public boolean destroyDependentInstance(T instance) { synchronized (dependentInstances) { for (Iterator<ContextualInstance<?>> iterator = dependentInstances.iterator(); iterator.hasNext();) { ContextualInstance<?> contextualInstance = iterator.next(); if (contextualIn...
python
def _teardown_log_prefix(self): """Tear down custom warning notification.""" self._logger_console_fmtter.prefix = '' self._logger_console_fmtter.plugin_id = '' self._logger_file_fmtter.prefix = ' ' self._logger_file_fmtter.plugin_id = ''
python
def list_connected_devices(self, **kwargs): """List connected devices. Example usage, listing all registered devices in the catalog: .. code-block:: python filters = { 'created_at': {'$gte': datetime.datetime(2017,01,01), '$lte': date...
java
private void logOutOfMemoryError() { logger.error("Dump some crucial information below:\n" + "Total milliseconds waiting for chunks: {},\n" + "Total memory used: {}, Max heap size: {}, total download time: {} millisec,\n" + "total parsing time: {} milliseconds, t...
java
public LineStringExpression<LineString> interiorRingN(int idx) { return GeometryExpressions.lineStringOperation(SpatialOps.INTERIOR_RINGN, mixin, ConstantImpl.create(idx)); }
java
public void setCaptionDescriptions(java.util.Collection<CaptionDescriptionPreset> captionDescriptions) { if (captionDescriptions == null) { this.captionDescriptions = null; return; } this.captionDescriptions = new java.util.ArrayList<CaptionDescriptionPreset>(captionDesc...
java
public ExpressRouteCircuitsRoutesTableListResultInner beginListRoutesTable(String resourceGroupName, String crossConnectionName, String peeringName, String devicePath) { return beginListRoutesTableWithServiceResponseAsync(resourceGroupName, crossConnectionName, peeringName, devicePath).toBlocking().single().bod...
java
private void doConnect() { try { LOG.info("Connecting to zookeeper server - " + RpcClientConf.ZK_SERVER_LIST); zkClient = new SimpleZooKeeperClient(RpcClientConf.ZK_SERVER_LIST, RpcClientConf.ZK_DIGEST_AUTH, new ServiceWatcher()); updateServiceLocalCa...
python
def patch_celery(): """ Monkey patch Celery to use cloudpickle instead of pickle. """ registry = serialization.registry serialization.pickle = cloudpickle registry.unregister('pickle') registry.register('pickle', cloudpickle_dumps, cloudpickle_loads, content_type='application/x...
java
public static void tint(View view, Tint tint) { final ColorStateList color = tint.getColor(view.getContext()); if (view instanceof ImageView) { tint(((ImageView) view).getDrawable(), color); } else if (view instanceof TextView) { TextView text = (TextView) view; ...
python
def _sequence(self, i): """Handle character group.""" result = ['['] end_range = 0 escape_hyphen = -1 removed = False last_posix = False c = next(i) if c in ('!', '^'): # Handle negate char result.append('^') c = next(...
java
public String currentWord() { return wordIndex >= 0 && wordIndex < words.size() ? words.get(wordIndex) : null; }
python
def _read_socket(self, size): """ Reads data from socket. :param size: Size in bytes to be read. :return: Data from socket """ value = b'' while len(value) < size: data = self.connection.recv(size - len(value)) if not data: ...
python
def check(self): """ Basic checks that don't depend on any context. Adapted from Bicoin Code: main.cpp """ self._check_tx_inout_count() self._check_txs_out() self._check_txs_in() # Size limits self._check_size_limit()
java
protected final BeanJsonMapperInfo getMapperInfo( JClassType beanType ) throws UnableToCompleteException { BeanJsonMapperInfo mapperInfo = typeOracle.getBeanJsonMapperInfo( beanType ); if ( null != mapperInfo ) { return mapperInfo; } boolean samePackage = true; Strin...
java
protected void readHeader(ByteBuffer buffer) { super.readHeader(buffer); if (this.responseStatus == ResponseStatus.NO_ERROR) { this.decodeStatus = BinaryDecodeStatus.DONE; } }
java
private JSONObject getTableResultHelper(String requestId, String resultType) { AipRequest request = new AipRequest(); preOperation(request); request.addBody("request_id", requestId); request.addBody("result_type", resultType); request.setUri(OcrConsts.TABLE_RESULT_GET); p...
java
public List<Label> getLabels(Object projectIdOrPath) throws GitLabApiException { return (getLabels(projectIdOrPath, getDefaultPerPage()).all()); }
java
@Deprecated public C verify(int allowedStatements, Query query) throws WrongNumberOfQueriesError { return verify(SqlQueries.exactQueries(allowedStatements).type(adapter(query))); }
java
@Override public Set<QueryableEntry<K, V>> filter(QueryContext queryContext) { if (!(predicate instanceof IndexAwarePredicate)) { return null; } Set<QueryableEntry<K, V>> set = ((IndexAwarePredicate<K, V>) predicate).filter(queryContext); if (set == null || set.isEmpty()...
python
def electron_shell_str(shell, shellidx=None): '''Return a string representing the data for an electron shell If shellidx (index of the shell) is not None, it will also be printed ''' am = shell['angular_momentum'] amchar = lut.amint_to_char(am) amchar = amchar.upper() shellidx_str = '' ...
python
def read_struct_field(self, struct_name, field_name, x, y, p=0): """Read the value out of a struct maintained by SARK. This method is particularly useful for reading fields from the ``sv`` struct which, for example, holds information about system status. See ``sark.h`` for details. ...
java
private void heartbeat() { long index = context.nextIndex(); long timestamp = System.currentTimeMillis(); replicator.replicate(new HeartbeatOperation(index, timestamp)) .thenRun(() -> context.setTimestamp(timestamp)); }
python
def insert_recording(hw): """Insert recording `hw` into database.""" mysql = utils.get_mysql_cfg() connection = pymysql.connect(host=mysql['host'], user=mysql['user'], passwd=mysql['passwd'], db=mysql['db'], ...
java
public static IUnitizingAnnotationUnit findNextUnit( final Iterator<IUnitizingAnnotationUnit> units, int raterIdx, final Object category) { while (units.hasNext()) { IUnitizingAnnotationUnit result = units.next(); if (category != null && !category.equals(result.getCategory())) { cont...
java
public static <T extends Annotation> T getAnnotation(Object context, Class<T> annotation) { Class<?> contextClass = context.getClass(); if(contextClass.isAnnotationPresent(annotation)) { return contextClass.getAnnotation(annotation); } else { return null; } }
java
@Given("^I obtain elasticsearch cluster name in '([^:]+?)(:.+?)?' and save it in variable '(.+?)'?$") public void saveElasticCluster(String host, String port, String envVar) throws Exception { commonspec.setRestProtocol("http://"); commonspec.setRestHost(host); commonspec.setRestPort(port);...
java
public double getRank(final double value) { if (isEmpty()) { return Double.NaN; } final DoublesSketchAccessor samples = DoublesSketchAccessor.wrap(this); long total = 0; int weight = 1; samples.setLevel(DoublesSketchAccessor.BB_LVL_IDX); for (int i = 0; i < samples.numItems(); i++) { if (s...
java
public void marshall(DeleteLabelsRequest deleteLabelsRequest, ProtocolMarshaller protocolMarshaller) { if (deleteLabelsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(deleteLabelsRequest.ge...
python
def _isbool(string): """ >>> _isbool(True) True >>> _isbool("False") True >>> _isbool(1) False """ return isinstance(string, _bool_type) or\ (isinstance(string, (_binary_type, _text_type)) and string in ("True", "False"))
java
public static final Long getTimeBoxValue(TimeZone zone, Date date) { if (date == null) return null; // use a Calendar in the specified timezone to figure out the // time which is edited in a format independent of TimeZone. Calendar cal = GregorianCalendar.getInstance(zone); cal...
java
@Override public int reverseProxyTo(URL url, StaplerRequest req) throws IOException { return getWrapped().reverseProxyTo(url, req); }
python
def get_team_members_with_extended_properties(self, project_id, team_id, top=None, skip=None): """GetTeamMembersWithExtendedProperties. [Preview API] Get a list of members for a specific team. :param str project_id: The name or ID (GUID) of the team project the team belongs to. :param st...
java
public void publish(boolean block, boolean skip) { //Sort components so we always get the same timline order... // Arrays.sort(components); //If blocking behavior has been requested, wait until any previous call //to the image encoding thread has finished. The rest of the //code in this function ...
java
private static synchronized IMqttClient getClient(MqttSettings settings) throws MqttException { if (CLIENT == null) { CLIENT = new MqttClient(settings.getServerUrl(), PUBLISHER_ID); MqttConnectOptions options = new MqttConnectOptions(); options.setAutomaticReconnect(true); options.setCleanSe...
python
def authenticate_with_password(self, username, password, security_question_id=None, security_question_answer=None): """Performs Username/Password Authentication :param string username: your SoftLayer username :param string pa...
python
def is_compression_coordinate(ds, variable): ''' Returns True if the variable is a coordinate variable that defines a compression scheme. :param netCDF4.Dataset nc: An open netCDF dataset :param str variable: Variable name ''' # Must be a coordinate variable if not is_coordinate_variabl...
java
public FlowStatus getFlowStatus(String flowName, String flowGroup, long flowExecutionId) { FlowStatus flowStatus = null; Iterator<JobStatus> jobStatusIterator = jobStatusRetriever.getJobStatusesForFlowExecution(flowName, flowGroup, flowExecutionId); if (jobStatusIterator.hasNext()) { flowStat...
java
@Override public AttachmentResourceWritable addAttachment(File file, AttachmentType type) throws RepositoryException { return addAttachment(file, type, file.getName()); }
java
public void getAllFileID(Callback<List<String>> callback) throws NullPointerException { gw2API.getAllFileIDs().enqueue(callback); }
python
def numpy_to_data_array(ary, *, var_name="data", coords=None, dims=None): """Convert a numpy array to an xarray.DataArray. The first two dimensions will be (chain, draw), and any remaining dimensions will be "shape". If the numpy array is 1d, this dimension is interpreted as draw If the numpy array...
python
def _fillAndTraceback(self, table): """ Perform Local Alignment according to Smith-Waterman Algorithm. Fills the table and then traces back from the highest score. NB left = deletion and up = insertion wrt seq1 """ # Fill max_score = 0 max_row = 0 ...
java
private void init() { // MarginLayoutParams marginParams = new ViewGroup.MarginLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) getContext().getResources().getDimension(R.dimen.bottom_navigation_padded_height))); // marginParams.setMargins(0, (int) getContext().getResour...
python
def set_value(self, dry_wet: LeakSensorState): """Set the value of the state to dry or wet.""" value = 0 if dry_wet == self._dry_wet_type: value = 1 self._update_subscribers(value)
java
@Override public int getJobInstanceCount(String jobName) throws NoSuchJobException, JobSecurityException { int jobInstanceCount = 0; if (authService == null || authService.isAdmin() || authService.isMonitor()) { // Do an unfiltered query if no app security, or if the user is admin or m...
java
protected static List<EndpointHelpDto> describeEndpoints(List<Class<? extends AbstractResource>> resourceClasses) { List<EndpointHelpDto> result = new LinkedList<>(); if (resourceClasses != null && !resourceClasses.isEmpty()) { for (Class<? extends AbstractResource> resourceClass : resource...
java
public static <T> Comparator<T> comparator(CheckedComparator<T> comparator, Consumer<Throwable> handler) { return (t1, t2) -> { try { return comparator.compare(t1, t2); } catch (Throwable e) { handler.accept(e); throw new Illeg...
java
public PreferencesFx saveSettings(boolean save) { preferencesFxModel.setSaveSettings(save); // if settings shouldn't be saved, clear them if there are any present if (!save) { preferencesFxModel.getStorageHandler().clearPreferences(); } return this; }
python
def stem_plural_word(self, plural): """Stem a plural word to its common stem form. Asian J. (2007) "Effective Techniques for Indonesian Text Retrieval" page 76-77. @link http://researchbank.rmit.edu.au/eserv/rmit:6312/Asian.pdf """ matches = re.match(r'^(.*)-(.*)$', plural) ...
python
def get_menu_items_for_rendering(self): """ Return a list of 'menu items' to be included in the context for rendering the current level of the menu. The responsibility for sourcing, priming, and modifying menu items is split between three methods: ``get_raw_menu_items()``, ...
python
def removeComments(element): """ Removes comments from the element and its children. """ global _num_bytes_saved_in_comments num = 0 if isinstance(element, xml.dom.minidom.Comment): _num_bytes_saved_in_comments += len(element.data) element.parentNode.removeChild(element) ...
java
public void removeRunner(String name, String identifier) throws GreenPepperServerException { log.debug("Removing runner: " + name); execute(XmlRpcMethodName.removeRunner, CollectionUtil.toVector(name), identifier); }
java
public synchronized void setActive(boolean active) { if (this.isActive == active) { log.info("DagManager already {}, skipping further actions.", (!active) ? "inactive" : "active"); return; } this.isActive = active; try { if (this.isActive) { log.info("Activating DagManager."); ...
java
public AssemblyDefinitionInner get(String resourceGroupName, String integrationAccountName, String assemblyArtifactName) { return getWithServiceResponseAsync(resourceGroupName, integrationAccountName, assemblyArtifactName).toBlocking().single().body(); }
java
public static Matcher<AnnotationTree> hasArgumentWithValue( String argumentName, Matcher<ExpressionTree> valueMatcher) { return new AnnotationHasArgumentWithValue(argumentName, valueMatcher); }
java
public void setSizeSegment(com.google.api.ads.admanager.axis.v201808.CreativePlaceholder[] sizeSegment) { this.sizeSegment = sizeSegment; }
python
def simple_eq(one: Instance, two: Instance, attrs: List[str]) -> bool: """ Test if two objects are equal, based on a comparison of the specified attributes ``attrs``. """ return all(getattr(one, a) == getattr(two, a) for a in attrs)
java
private void loadPreInstalledPlugins() { for (File file : listJarFiles(fs.getInstalledPluginsDir())) { PluginInfo info = PluginInfo.create(file); registerPluginInfo(info); } }
python
def _cache_loc(self, path, saltenv='base', cachedir=None): ''' Return the local location to cache the file, cache dirs will be made ''' cachedir = self.get_cachedir(cachedir) dest = salt.utils.path.join(cachedir, 'files', ...
python
def _postcheck(self, network, feedin): """ Raises an error if the curtailment of a generator exceeds the feed-in of that generator at any time step. Parameters ----------- network : :class:`~.grid.network.Network` feedin : :pandas:`pandas.DataFrame<dataframe>` ...
python
def _load_config(): """Helper to load prefs from ~/.vispy/vispy.json""" fname = _get_config_fname() if fname is None or not op.isfile(fname): return dict() with open(fname, 'r') as fid: config = json.load(fid) return config
java
@Override public synchronized SQLiteDatabase getReadableDatabase() { if (mDatabase != null && mDatabase.isOpen()) { return mDatabase; // The database is already open for business } if (mIsInitializing) { throw new IllegalStateException("getReadableDatabase ca...
java
public static com.liferay.commerce.model.CommerceOrderItem addCommerceOrderItem( com.liferay.commerce.model.CommerceOrderItem commerceOrderItem) { return getService().addCommerceOrderItem(commerceOrderItem); }
python
def summarize(self, test_arr, vectorizable_token, sentence_list, limit=5): ''' Summarize input document. Args: test_arr: `np.ndarray` of observed data points.. vectorizable_token: is-a `VectorizableToken`. sentence_list: `lis...
python
def clear_expired_cookies(self): """Discard all expired cookies. You probably don't need to call this method: expired cookies are never sent back to the server (provided you're using DefaultCookiePolicy), this method is called by CookieJar itself every so often, and the .save() ...
java
@Override @Deprecated public DescribeExportConfigurationsResult describeExportConfigurations(DescribeExportConfigurationsRequest request) { request = beforeClientExecution(request); return executeDescribeExportConfigurations(request); }
java
public static JPAEntry convertEDBObjectEntryToJPAEntry(EDBObjectEntry entry, JPAObject owner) { for (EDBConverterStep step : steps) { if (step.doesStepFit(entry.getType())) { LOGGER.debug("EDBConverterStep {} fit for type {}", step.getClass().getName(), entry.getType()); ...
java
public Reader requestPost(String data) throws IOException { connection.setRequestMethod("POST"); connection.setDoOutput(true); Writer writer = new Writer(connection.getOutputStream()); writer.write(data); writer.close(); return new Reader(connection.getInputSt...
java
protected static void addHeaders(Selenified clazz, ITestContext context, Map<String, Object> headers) { context.setAttribute(clazz.getClass().getName() + "Headers", headers); }
java
public List<String> getTableColumn(final By tableBy, final int columnNumber) { List<String> result = new ArrayList<String>(); List<List<String>> table = this.getTableAsList(tableBy); for (List<String> line : table) { result.add(line.get(columnNumber)); } return result; }
java
public void marshall(DeleteClientCertificateRequest deleteClientCertificateRequest, ProtocolMarshaller protocolMarshaller) { if (deleteClientCertificateRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshalle...
java
public CompletableFuture<String> getScope(final String scopeName) { Preconditions.checkNotNull(scopeName); return streamStore.getScopeConfiguration(scopeName); }
java
public String getValue (String name, String defval) { return _props.getProperty(name, defval); }
java
@Override public FieldTextBuilder NOT() { // NOT * => 0 // NOT 0 => * if(isEmpty()) { return setFieldText(MATCHNOTHING); } if(MATCHNOTHING.equals(this)) { return clear(); } not ^= true; return this; }
python
def emit(self, record): """ Overloaded emit() function from the logger module. The supplied log record is added to the log buffer and the sigNewLog signal triggered. .. note:: this method is always only called from the ``logger`` module. """ self.log.a...
java
public static <T> MutableFloatCollection collectFloat( Iterable<T> iterable, FloatFunction<? super T> floatFunction) { if (iterable instanceof MutableCollection) { return ((MutableCollection<T>) iterable).collectFloat(floatFunction); } if (iterable...
python
def createEditor(self, parent, column, operator, value): """ Creates a new editor for the given parent and operator. :param parent | <QWidget> operator | <str> value | <variant> """ editor = super(Numeric...
java
public void informDiscard(final EventDispatcher pDispatcher, final Path pFile) { // Remove the checksum resource to save memory resources.remove(pFile); if (pDispatcher.hasListeners()) { final Collection<DispatchKey> keys = createKeys(pFile); keys.forEach(k -> pDispatche...
python
def read_rtt(jlink): """Reads the JLink RTT buffer #0 at 10Hz and prints to stdout. This method is a polling loop against the connected JLink unit. If the JLink is disconnected, it will exit. Additionally, if any exceptions are raised, they will be caught and re-raised after interrupting the main t...
python
def build_kernel(self): """Build the KNN kernel. Build a k nearest neighbors kernel, optionally with alpha decay. If `precomputed` is not `None`, the appropriate steps in the kernel building process are skipped. Must return a symmetric matrix Returns ------- ...
python
def plot_lr(self, show_moms=False, skip_start:int=0, skip_end:int=0, return_fig:bool=None)->Optional[plt.Figure]: "Plot learning rate, `show_moms` to include momentum." lrs = self._split_list(self.lrs, skip_start, skip_end) iterations = self._split_list(range_of(self.lrs), skip_start, skip_end) ...
java
public void generateProxy(Element element) { try { getClassBuilder(element) .buildProxyClass() .build() .writeTo(filer); } catch (Exception ex) { messager.printMessage(Diagnostic.Kind.WARNING, "Error while generat...
java
public Postcard withParcelableArray(@Nullable String key, @Nullable Parcelable[] value) { mBundle.putParcelableArray(key, value); return this; }