language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static String encode(final byte[] input) { char[] chars = encode(input, input.length); return new String(chars); }
java
private void genImportCode(ClassCode code) { code.importClass("java.util.*"); code.importClass("java.io.IOException"); code.importClass("java.lang.reflect.*"); code.importClass("com.baidu.bjf.remoting.protobuf.code.*"); code.importClass("com.baidu.bjf.remoting.protobuf.utils.*");...
java
public MetadataBuilder addDataSource(@NotNull InputStream dataSource, String path, boolean closeAfterBuild) { checkHashingResultIsNotSet(); filesPaths.add(path); dataSources.add(new StreamBasedHolderImpl(dataSource, closeAfterBuild)); return this; }
python
def short_repr(obj, max_len=40): """Returns a short, term-friendly string representation of the object. Args: obj: An object for which to return a string representation. max_len: Maximum length of the returned string. Longer reprs will be turned into a brief descriptive string giving the type and l...
java
public ServiceFuture<DataLakeStoreAccountInner> beginUpdateAsync(String resourceGroupName, String accountName, UpdateDataLakeStoreAccountParameters parameters, final ServiceCallback<DataLakeStoreAccountInner> serviceCallback) { return ServiceFuture.fromResponse(beginUpdateWithServiceResponseAsync(resourceGroupN...
java
private void addProxyExtras(TypeSpec.Builder classBuilder) { addRemoterProxyMethods(classBuilder); addProxyDeathMethod(classBuilder, "linkToDeath", "Register a {@link android.os.IBinder.DeathRecipient} to know of binder connection lose\n"); addProxyDeathMethod(classBuilder, "unlinkToDeath", "...
java
public static String convertToString(final Collection collection, final String prefix, final String postfix) { StringBuilder builder = new StringBuilder(); for (Object o : collection) { builder.append(prefix).append(o).append(postfix); } return builder.toString(); }
python
def convert_string(string): """Convert string to int, float or bool. """ if is_int(string): return int(string) elif is_float(string): return float(string) elif convert_bool(string)[0]: return convert_bool(string)[1] elif string == 'None': return None else: ...
python
def get_query_dict(self, **kwargs): """ function to generate a filter dictionary, in which the key is the keyword used in django filter function in string form, and the value is the searched value. :param kwargs:dict: query dict sent by data tables package :return: dict:...
java
public ServiceFuture<KeyBundle> importKeyAsync(String vaultBaseUrl, String keyName, JsonWebKey key, final ServiceCallback<KeyBundle> serviceCallback) { return ServiceFuture.fromResponse(importKeyWithServiceResponseAsync(vaultBaseUrl, keyName, key), serviceCallback); }
java
public void marshall(DescribeChapCredentialsRequest describeChapCredentialsRequest, ProtocolMarshaller protocolMarshaller) { if (describeChapCredentialsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshalle...
python
def select_ocv_points(cellpydata, cycles=None, selection_method="martin", number_of_points=5, interval=10, relative_voltage=False, report_times=False, direction=None): """Select points from the ocvrlx step...
java
@Override public void onDown(HumanInputEvent<?> event) { if (dragging && leftWidget) { // mouse was moved outside of widget doSelect(event); } else if (!isRightMouseButton(event)) { // no point trying to select when there is no active layer dragging = true; leftWidget = false; timestamp = new Da...
java
public IfcSpaceHeaterTypeEnum createIfcSpaceHeaterTypeEnumFromString(EDataType eDataType, String initialValue) { IfcSpaceHeaterTypeEnum result = IfcSpaceHeaterTypeEnum.get(initialValue); if (result == null) throw new IllegalArgumentException( "The value '" + initialValue + "' is not a valid enumerator o...
java
public static Object readNativeValue(Type type, Block block, int position) { Class<?> javaType = type.getJavaType(); if (block.isNull(position)) { return null; } if (javaType == long.class) { return type.getLong(block, position); } if (javaTyp...
python
def run(self): """Run the example consumer by connecting to RabbitMQ and then starting the IOLoop to block and allow the SelectConnection to operate. """ logger.debug('Running rabbit consumer') self._connection = self.connect() self._connection.ioloop.start()
python
def _check_split_list_validity(self): """ See _temporal_split_list above. This function checks if the current split lists are still valid. """ # FIXME: Currently very primitive, but needs to be fast if not (hasattr(self,"_splitListsSet") and (self._splitListsSet)): ...
java
public ActiveTunnel[] getRemoteForwardingTunnels() throws IOException { Vector<ActiveTunnel> v = new Vector<ActiveTunnel>(); String[] remoteForwardings = getRemoteForwardings(); for (int i = 0; i < remoteForwardings.length; i++) { ActiveTunnel[] tmp = getRemoteForwardingTunnels(remoteForwardings[i]); for (i...
java
private int getQuoteToken( String content, int startOffset, int endOffset ) { String quoteDelimiter = content.substring( startOffset, startOffset + 1 ); int index; int endOfQuote = startOffset; int endOfToken = startOffset + 1; while( endOfToken <= endOffset ) { if( isDelimiter( content....
java
@Override public void setTermsOfUseContent(String termsOfUseContent, java.util.Locale locale, java.util.Locale defaultLocale) { _cpDefinitionVirtualSetting.setTermsOfUseContent(termsOfUseContent, locale, defaultLocale); }
java
private static char getChar(final String signature, int pos) { return pos < signature.length() ? signature.charAt(pos) : (char) 0; }
java
public void addColumn(int spacing) { table.addCell("&nbsp","width="+spacing); column = new Table(0); table.addCell(column); table.cell().top(); columns++; }
java
private static void setEnv(Map<String, String> newEnv, boolean overwrite) { for (Entry<String, String> entry : newEnv.entrySet()) { if (overwrite || System.getProperty(entry.getKey()) != null) { System.setProperty(entry.getKey(), entry.getValue()); } } if (!overwrite) { Iterator<Entry<String, Strin...
python
def parse_constant(self, node): """ Parses <Constant> @param node: Node containing the <Constant> element @type node: xml.etree.Element """ try: name = node.lattrib['name'] except: self.raise_error('<Constant> must specify a name.') ...
java
@Override public void process(Node externs, Node root) { ReferenceCollectingCallback callback = new ReferenceCollectingCallback(compiler, ReferenceCollectingCallback.DO_NOTHING_BEHAVIOR, new Es6SyntacticScopeCreator(compiler)); callback.process(root); for (Var variable : callback.getAllS...
java
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { mpssession_responses result = (mpssession_responses) service.get_payload_formatter().string_to_resource(mpssession_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == S...
python
def runner(fun, arg=None, timeout=5): ''' Execute a runner on the master and return the data from the runner function CLI Example: .. code-block:: bash salt publish.runner manage.down ''' arg = _parse_args(arg) if 'master_uri' not in __opts__: return 'No access to mas...
python
def applyMassCalMs1(msrunContainer, specfile, dataFit, **kwargs): """Applies a correction function to the MS1 ion m/z arrays in order to correct for a m/z dependent m/z error. :param msrunContainer: intance of :class:`maspy.core.MsrunContainer`, containing the :class:`maspy.core.Sai` items of the "...
java
public static String getStringInitParameter(ExternalContext context, String[] names) { return getStringInitParameter(context, names, null); }
python
def _decode_list(data): """ 解析json列表,转换成utf-8 """ if six.PY3: return data rv = [] for item in data: if not isinstance(item, text_type): item = item.encode('utf-8') elif isinstance(item, list): item = _decode_list(item) rv.append(item) r...
python
def RS(S, second_pass=False): """Compute a C/F splitting using Ruge-Stuben coarsening Parameters ---------- S : csr_matrix Strength of connection matrix indicating the strength between nodes i and j (S_ij) second_pass : bool, default False Perform second pass of classical AM...
python
def cv(data, channels=None): """ Calculate the Coeff. of Variation of the events in an FCSData object. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : int or ...
python
def _setauto(self, s, length, offset): """Set bitstring from a bitstring, file, bool, integer, array, iterable or string.""" # As s can be so many different things it's important to do the checks # in the correct order, as some types are also other allowed types. # So basestring must be ...
python
def register(self, _type, _format, creater, _2nd_pass=None): """ register a type/format handler when producing primitives example function to create a byte primitive: ```python def create_byte(obj, val, ctx): # val is the value used to create this primitive, for example, a ...
python
def get_index(cls): """Gets the index for this model. The index for this model is specified in `settings.ES_INDEXES` which is a dict of mapping type -> index name. By default, this uses `.get_mapping_type()` to determine the mapping and returns the value in `settings.ES_INDEXES...
java
private Shape createCheckMark(int x, int y, int size) { int markSize = (int) (size * SIZE_MULTIPLIER + 0.5); int markX = x + (int) (size * X_MULTIPLIER + 0.5); int markY = y + (int) (size * Y_MULTIPLIER + 0.5); return shapeGenerator.createCheckMark(markX, markY, markSize, markSize...
java
@SuppressWarnings({ "unchecked" }) /* package */<T> HystrixCachedObservable<T> get(String cacheKey) { ValueCacheKey key = getRequestCacheKey(cacheKey); if (key != null) { ConcurrentHashMap<ValueCacheKey, HystrixCachedObservable<?>> cacheInstance = requestVariableForCache.get(concurrencyS...
python
def ensure_edit_id(self): """create edit id if edit id is None.""" if self.edit_id is None: edit_request = self.edits().insert( body={}, packageName=self.package_name) result = edit_request.execute() self.edit_id = result['id']
python
def setup_script_logging(): """ Use this logger for standalone scripts, or script-like subcommands, such as bcbio_prepare_samples and bcbio_nextgen.py -w template. """ handlers = [logbook.NullHandler()] format_str = ("[{record.time:%Y-%m-%dT%H:%MZ}] " "{record.level_name}: {rec...
java
public String[] splitString(String text, int maxChars) { String[] splitVals = {" "}; return splitString(text,maxChars,splitVals); }
python
def load(self): """ load all feature into memory Returns ------- """ self.layer.ResetReading() for i in range(self.nfeatures): if self.__features[i] is None: self.__features[i] = self.layer[i]
java
private static <T> T filterBySupportedProperties( Class<T> factoryClass, Map<String, String> properties, List<TableFactory> foundFactories, List<TableFactory> classFactories) { final List<String> plainGivenKeys = new LinkedList<>(); properties.keySet().forEach(k -> { // replace arrays with wildcard S...
java
public FEELFnResult<Object> evaluate(EvaluationContext ctx, Object[] params) { if ( decisionRules.isEmpty() ) { return FEELFnResult.ofError(new FEELEventBase(Severity.WARN, "Decision table is empty", null)); } Object[] actualInputs = resolveActualInputs( ctx, feel ); ...
python
def check_cf_role(self, ds): """ Check variables defining cf_role for legal cf_role values. §9.5 The only acceptable values of cf_role for Discrete Geometry CF data sets are timeseries_id, profile_id, and trajectory_id :param netCDF4.Dataset ds: An open netCDF dataset :...
java
private StringBuilder debugDumpCandidates(StringBuilder msg, List<? extends Itemset> candidates, VectorFieldTypeInformation<BitVector> meta) { msg.append(':'); for(Itemset itemset : candidates) { msg.append(" ["); itemset.appendTo(msg, meta); msg.append(']'); } return msg; }
java
public Method getEventMethod(Class controlInterface) { // // If we already hold a method reference and its loader matches up with the input // interface, then just return it. // if (_method != null && _method.getDeclaringClass().getClassLoader().equals(controlInte...
java
public java.lang.String getErrorStyle() { return (java.lang.String) getStateHelper().eval(PropertyKeys.errorStyle); }
python
def keys(self): """List of reader's keys. """ keys = [] for val in self.form.scales.values(): keys += val.dtype.fields.keys() return keys
java
public BatchXMLDescriptor addNamespace(String name, String value) { model.attribute(name, value); return this; }
java
public T execute(Connection conn) { // 封装socket交易 send try { send(conn.getOutputStream(), conn.getCharset()); } catch (IOException e) { LOGGER.error("send conent error", e); throw new FdfsIOException("socket io exception occured while sending cmd", e); ...
python
def find_one(cls, *args, **kwargs): """Same as ``collection.find_one``, returns model object instead of dict.""" d = cls.collection.find_one(*args, **kwargs) if d: return cls(**d)
python
def density_hub(self, weather_df): r""" Calculates the density of air at hub height. The density is calculated using the method specified by the parameter `density_model`. Previous to the calculation of the density the temperature at hub height is calculated using the method spe...
python
def main_passpersist(self): """ Main function that handle SNMP's pass_persist protocol, called by the start method. Direct call is unnecessary. """ line = sys.stdin.readline().strip() if not line: raise EOFError() if 'PING' in line: print("PONG") elif 'getnext' in line: oid = self.cut_oid(sy...
java
public static ZMatrixRMaj[] columnsToVector(ZMatrixRMaj A, ZMatrixRMaj[] v) { ZMatrixRMaj[]ret; if( v == null || v.length < A.numCols ) { ret = new ZMatrixRMaj[ A.numCols ]; } else { ret = v; } for( int i = 0; i < ret.length; i++ ) { if( r...
java
public final Optional<PluginInformation> getInformation(String pluginName) { Require.nonNull(pluginName, "pluginName"); return Optional.ofNullable(this.information.get(pluginName)); }
python
def push_record_set(self, **kwargs): """ Push build config set record to Brew. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def ca...
java
public final GroupFindingsPagedResponse groupFindings(SourceName parent, String groupBy) { GroupFindingsRequest request = GroupFindingsRequest.newBuilder() .setParent(parent == null ? null : parent.toString()) .setGroupBy(groupBy) .build(); return groupFindings(reques...
java
public void marshall(RecordDetail recordDetail, ProtocolMarshaller protocolMarshaller) { if (recordDetail == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(recordDetail.getRecordId(), RECORDID_BINDIN...
python
def box_iter(self): """Get an iterator over all boxes in the Sudoku""" for i in utils.range_(self.order): for j in utils.range_(self.order): yield self.box(i * 3, j * 3)
java
public Table replaceColumn(final String columnName, final Column<?> newColumn) { int colIndex = columnIndex(columnName); return replaceColumn(colIndex, newColumn); }
java
public String signRequest(String urlString, byte[] body, String contentType) { URI uri = URI.create(urlString); String path = uri.getRawPath(); String query = uri.getRawQuery(); Mac mac = createMac(); mac.update(StringUtils.utf8Bytes(path)); if (query != null && query....
java
@Override public String readLine() throws IOException { StringBuilder lineBuilder = new StringBuilder(); EditorOperation operation; while (true) { operation = readOperation(); switch (operation.getType()) { case BACKSAPCE: case DELETE: ...
python
def htmlParseDoc(cur, encoding): """parse an HTML in-memory document and build a tree. """ ret = libxml2mod.htmlParseDoc(cur, encoding) if ret is None:raise parserError('htmlParseDoc() failed') return xmlDoc(_obj=ret)
java
private void handleExpansionRequest(final Request request) { String[] paramValue = request.getParameterValues(getId() + ".expanded"); if (paramValue == null) { paramValue = new String[0]; } String[] expandedRows = removeEmptyStrings(paramValue); List<Integer> oldExpansions = getExpandedRows(); List<In...
python
def check_expected_errors(self, test_method): """ This method is called after each test. It will read decorated informations and check if there are expected errors. You can set expected errors by decorators :py:func:`.expected_error_page`, :py:func:`.allowed_error_pages`, :py:fu...
java
@SuppressWarnings("checkstyle:anoninnerlength") protected StringConcatenationClient generateAccessors(Set<String> addedKeywords, Map<String, String> getters) { return new StringConcatenationClient() { @SuppressWarnings("synthetic-access") @Override protected void appendTo(TargetStringConcatenation it) { ...
java
private static boolean getInternalPublicMethods(Class<?> cls, Map<Signature, Method> sigs) { Method[] methods = null; try { /* * This class or interface is non-public so we * can't use any of it's methods. Go back ...
python
def read(file_path): """ Read a gmt file at the path specified by file_path. Args: file_path (string): path to gmt file Returns: gmt (GMT object): list of dicts, where each dict corresponds to one line of the GMT file """ # Read in file actual_file_path = os.path.e...
python
def try_enqueue(conn, queue_name, msg): """ Try to enqueue a message. If it succeeds, return the message ID. :param conn: SQS API connection :type conn: :py:class:`botocore:SQS.Client` :param queue_name: name of queue to put message in :type queue_name: str :param msg: JSON-serialized messa...
java
public ASMifier visitAnnotation(final String desc, final boolean visible) { buf.setLength(0); buf.append("{\n").append("av0 = ").append(name) .append(".visitAnnotation("); appendConstant(desc); buf.append(", ").append(visible).append(");\n"); text.add(buf.toString...
java
@Override public List<CommerceTierPriceEntry> findByCommercePriceEntryId( long commercePriceEntryId) { return findByCommercePriceEntryId(commercePriceEntryId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); }
python
def get_foreign_page_id_from_type(self, page_type): ''' Get the foreign page id based on type Only works for index pages ''' # TODO: log this response = requests.get("{}pages/?type={}".format( self.api_url, page_type)) content = json.loads(response.co...
java
public void write(File f) { try { ObjectOutputStream oos = new ObjectOutputStream(new GZIPOutputStream(new FileOutputStream(f))); oos.writeObject(textDirection); if (textDirection.doForward()) oos.writeObject(forwardCRF); if (te...
java
private static void writeElementNoTag( final CodedOutputStream output, final WireFormat.FieldType type, final Object value) throws IOException { switch (type) { case DOUBLE : output.writeDoubleNoTag ((Double ) value); break; case FLOAT : output.writeFloatNoTag ((Float ) ...
python
def serialize(self, data, fmt='%10.7E'): """ Serialize a collection of ground motion fields to XML. :param data: An iterable of "GMF set" objects. Each "GMF set" object should: * have an `investigation_time` attribute * have an `stochastic_event_...
java
public static void init(@NonNull Application app, @NonNull CoreConfiguration config) { init(app, config, true); }
python
def set_sync_limit(self, limit: int) -> Optional[int]: """ Sets the events limit per room for sync and return previous limit """ try: prev_limit = json.loads(self.sync_filter)['room']['timeline']['limit'] except (json.JSONDecodeError, KeyError): prev_limit = None ...
java
static <T> AvroFactory<T> create(Class<T> type, @Nullable Schema currentSchema, @Nullable Schema previousSchema) { final ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (SpecificRecord.class.isAssignableFrom(type)) { return fromSpecific(type, cl, Optional.ofNullable(previousSchema)); } i...
java
public static List<String> getUnknownFeatures(HColumnDescriptor columnDescriptor) { List<String> unknownFeatures = new ArrayList<String>(); for (Map.Entry<String, String> entry : columnDescriptor.getConfiguration().entrySet()) { String key = entry.getKey(); if (!SUPPORTED_OPTION_KEYS.contains(key) ...
python
def train(args): """Training helper.""" vocab, row, col, counts = get_train_data(args) model = GloVe(token_to_idx=vocab.token_to_idx, output_dim=args.emsize, dropout=args.dropout, x_max=args.x_max, alpha=args.alpha, weight_initializer=mx.init.Uniform(scale=1 / args.emsize...
python
def remove_outOfBound(self, data, lowBound, highBound): """ Remove out of bounds data from input dataframe. Parameters ---------- data : pd.DataFrame() Input dataframe. lowBound : float Lower bound for dataframe. highBound : float ...
python
def itemAt( self, index ): """ Returns the rollout item at the inputed index. :return <XRolloutItem> || None """ layout = self.widget().layout() if ( 0 <= index and index < (layout.count() - 1) ): return layout.itemAt(index).widget() retur...
java
public static String getTaskLogsUrl(JobHistory.TaskAttempt attempt) { if (attempt.get(Keys.HTTP_PORT).equals("") || attempt.get(Keys.TRACKER_NAME).equals("") || attempt.get(Keys.TASK_ATTEMPT_ID).equals("")) { return null; } String taskTrackerName = JobInProgress.convertTrackerNa...
python
def get_state(self, **kwargs): '''Return the current :class:`ModelState` for this :class:`Model`. If ``kwargs`` parameters are passed a new :class:`ModelState` is created, otherwise it returns the cached value.''' dbdata = self.dbdata if 'state' not in dbdata or kwargs: dbdata[...
python
def _restore_clipboard_text(self, backup: str): """Restore the clipboard content.""" # Pasting takes some time, so wait a bit before restoring the content. Otherwise the restore is done before # the pasting happens, causing the backup to be pasted instead of the desired clipboard content. ...
java
boolean removeBlock(BlockInfo b) { blockList = b.listRemove(blockList, this); if ( b.removeNode(this) ) { numOfBlocks--; return true; } else { return false; } }
python
def run_step(context): """Get, set, unset $ENVs. Context is a dictionary or dictionary-like. context is mandatory. Input context is: env: get: {dict} set: {dict} unset: [list] At least one of env's sub-keys (get, set or unset) must exist. This step wil...
java
@SuppressWarnings("synthetic-access") @Pure public EulerAngles getEulerAngles(CoordinateSystem3D system) { // See http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToEuler/index.htm // Standard used: XZY_RIGHT_HAND Quaternion q = new Quaternion(this); system.toSystem(q, CoordinateSy...
python
def compressBWT(inputFN, outputFN, numProcs, logger): ''' Current encoding scheme uses 3 LSB for the letter and 5 MSB for a count, note that consecutive ones of the same character combine to create one large count. So to represent 34A, you would have 00010|001 followed by 00001|001 which can be though of ...
java
public synchronized Statement createStatement() throws SQLException { checkClosed(); Statement stmt = new JDBCStatement(this, JDBCResultSet.TYPE_FORWARD_ONLY, JDBCResultSet.CONCUR_READ_ONLY, rsHoldability); return stmt; }
python
def users(self): """ Gets the Users API client. Returns: Users: """ if not self.__users: self.__users = Users(self.__connection) return self.__users
java
public static Field getFieldFromClass(String field, Class<? extends Object> clazz) { try { return clazz.getDeclaredField(field); } catch (Exception e) { try { return clazz.getField(field); } catch (Exception ex) { } } return...
java
public static String getDisplayVariant(String localeID, String displayLocaleID){ return getDisplayVariantInternal(new ULocale(localeID), new ULocale(displayLocaleID)); }
python
def checkNewCheckpointsAreLeafVertices(self): """ A checkpoint job is a job that is restarted if either it fails, or if any of \ its successors completely fails, exhausting their retries. A job is a leaf it is has no successors. A checkpoint job must be a leaf when initially ad...
python
def align(self, referencewords, datatuple): """align the reference sentence with the tagged data""" targetwords = [] for i, (word,lemma,postag) in enumerate(zip(datatuple[0],datatuple[1],datatuple[2])): if word: subwords = word.split("_") for w in subw...
python
def skeleton(files, metadata, sqlite_extensions): "Generate a skeleton metadata.json file for specified SQLite databases" if os.path.exists(metadata): click.secho( "File {} already exists, will not over-write".format(metadata), bg="red", fg="white", bold=T...
python
def pull_buildpack(url): """ Update a buildpack in its shared location, then make a copy into the current directory, using an md5 of the url. """ defrag = _defrag(urllib.parse.urldefrag(url)) with lock_or_wait(defrag.url): bp = update_buildpack(url) dest = bp.basename + '-' + has...
python
def qry_helper(flag_id, qry_string, param_str, flag_filt=False, filt_st=""): """Dynamically add syntaxtical elements to query. This functions adds syntactical elements to the query string, and report title, based on the types and number of items added thus far. Args: flag_filt (bool): at least...
java
@NonNull public Transition addTarget(@Nullable Class targetType) { if (targetType != null) { if (mTargetTypes == null) { mTargetTypes = new ArrayList<Class>(); } mTargetTypes.add(targetType); } return this; }
java
@Override public ChannelFuture block( InetAddress multicastAddress, NetworkInterface networkInterface, InetAddress sourceToBlock, ChannelPromise promise) { checkJavaVersion(); if (multicastAddress == null) { throw new NullPointerException("multicastAddress"); ...