language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
private String extractPathFromUrl(String url) { String path = url.replaceAll(".+://.+?(?=/)", ""); if (!path.startsWith("/")) { throw new RuntimeException("Path must start with '/': " + path); } return path; }
python
def request_and_check(self, url, method='get', expected_content_type=None, **kwargs): """Performs a request, and checks that the status is OK, and that the content-type matches expectations. Args: url: URL to request method: either 'get' or 'post' ...
python
def _make_image_description(self, datasets, **kwargs): """ generate image description for mitiff. Satellite: NOAA 18 Date and Time: 06:58 31/05-2016 SatDir: 0 Channels: 6 In this file: 1-VIS0.63 2-VIS0.86 3(3B)-IR3.7 4-IR10.8 5-IR11.5 6(3A)-VIS1.6 Xsize...
python
def get(self, path, params=None): """Make a GET request, optionally including a parameters, to a path. The path of the request is the full URL. Parameters ---------- path : str The URL to request params : DataQuery, optional The query to pass whe...
java
private void obtainPositiveButtonText(@NonNull final TypedArray typedArray) { setPositiveButtonText( typedArray.getText(R.styleable.DialogPreference_android_positiveButtonText)); }
python
def cto(self): """ The final character position in the surface string. Defaults to -1 if there is no valid cto value. """ cto = -1 try: if self.lnk.type == Lnk.CHARSPAN: cto = self.lnk.data[1] except AttributeError: pass #...
java
private static String normalizeClusterUrl(String clusterIdentifier) { try { URI uri = new URI(clusterIdentifier.trim()); // URIs without protocol prefix if (!uri.isOpaque() && null != uri.getHost()) { clusterIdentifier = uri.getHost(); } else { clusterIdentifier = uri.toStrin...
java
void setPageIndexAsString(String pageIndex) { if (CmsStringUtil.isEmpty(pageIndex)) { return; } try { m_pageIndex = Integer.parseInt(pageIndex); } catch (NumberFormatException e) { // intentionally left blank } }
python
def columns(self): """ Returns the list of column names that this index will be expecting as \ inputs when it is called. :return [<str>, ..] """ schema = self.schema() return [schema.column(col) for col in self.__columns]
python
def should_skip(app, what, name, obj, skip, options): """ Callback object chooser function for docstring documentation. """ if name in ["__doc__", "__module__", "__dict__", "__weakref__", "__abstractmethods__" ] or name.startswith("_abc_"): return True return False
java
public List<IWord> getWordList() { List<IWord> wordList = new LinkedList<IWord>(); for (Sentence sentence : sentenceList) { wordList.addAll(sentence.wordList); } return wordList; }
java
private static int createDFSPaths() { String basePath = new String(TEST_BASE_DIR) + "/" + hostName_ + "_" + processName_; try { long startTime = System.nanoTime(); Boolean ret = dfsClient_.mkdirs(basePath); timingMkdirs_.add(new Double((System.nanoTime() - startTime)/(1E9))); if (!ret)...
java
public static MonitorAndManagementSettings newInstance(URL settingsXml) throws IOException, JAXBException { InputStream istream = settingsXml.openStream(); JAXBContext ctx = JAXBContext.newInstance(MonitorAndManagementSettings.class); return (MonitorAndManagementSettings) ctx.createUnmarshaller(...
java
public static void startPollingForMessages(final String queueURL) { if (!StringUtils.isBlank(queueURL) && !POLLING_THREADS.containsKey(queueURL)) { logger.info("Starting SQS river using queue {} (polling interval: {}s)", queueURL, POLLING_INTERVAL); POLLING_THREADS.putIfAbsent(queueURL, Para.getExecutorService(...
python
def convert_to_push(ir, node): """ Convert a call to a PUSH operaiton The funciton assume to receive a correct IR The checks must be done by the caller May necessitate to create an intermediate operation (InitArray) Necessitate to return the lenght (see push documentation) As a result, the...
python
def find_nested_models(self, model, definitions): ''' Prepare dictionary with reference to another definitions, create one dictionary that contains full information about model, with all nested reference :param model: --dictionary that contains information about model :type model...
java
@SuppressWarnings("all") public void validateFalse(boolean value, String name, String message) { if (value) { addError(name, Optional.ofNullable(message).orElse(messages.get(Validation.FALSE_KEY.name(), name))); } }
python
def get_etf_records(self, etf_name, offset, limit, _async=False): """ 查询etf换入换出明细 :param etf_name: eth基金名称 :param offset: 开始位置,0为最新一条 :param limit: 返回记录条数(0, 100] :param _async: :return: """ params = {} path = '/etf/list' params['...
python
def get_scaled_f_scores(self, category, scaler_algo=DEFAULT_SCALER_ALGO, beta=DEFAULT_BETA): ''' Computes scaled-fscores Parameters ---------- category : str category name to score sca...
python
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'key') and self.key is not None: _dict['key'] = self.key if hasattr(self, 'matching_results') and self.matching_results is not None: _dict['m...
python
def verify_token(self, token, requested_access): """ Check the token bearer is permitted to access the resource :param token: Access token :param requested_access: the access level the client has requested :returns: boolean """ client = API(options.url_auth, ...
python
def _numbers_units(N): """ >>> _numbers_units(45) '123456789012345678901234567890123456789012345' """ lst = range(1, N + 1) return "".join(list(map(lambda i: str(i % 10), lst)))
java
private static Expression buildAccessChain( Expression base, CodeChunk.Generator generator, Iterator<ChainAccess> chain) { if (!chain.hasNext()) { return base; // base case } ChainAccess link = chain.next(); if (link.nullSafe) { if (!base.isCheap()) { base = generator.declarati...
python
def GetFileEntryByPathSpec(self, path_spec): """Retrieves a file entry for a path specification. Args: path_spec (PathSpec): a path specification. Returns: CompressedStreamFileEntry: a file entry or None if not available. """ return compressed_stream_file_entry.CompressedStreamFileEntr...
python
def unpack(self, buff, offset=0): """Unpack a binary message into this object's attributes. Unpack the binary value *buff* and update this object attributes based on the results. Args: buff (bytes): Binary data package to be unpacked. offset (int): Where to begi...
python
def profiler_set_config(mode='symbolic', filename='profile.json'): """Set up the configure of profiler (Deprecated). Parameters ---------- mode : string, optional Indicates whether to enable the profiler, can be 'symbolic', or 'all'. Defaults to `symbolic`. filename : string, option...
python
def reset(self): """Resets simulation.""" # TODO(yukez): investigate black screen of death # if there is an active viewer window, destroy it self._destroy_viewer() self._reset_internal() self.sim.forward() return self._get_observation()
python
def is_zero_user(self): """返回当前用户是否为三零用户,其实是四零: 赞同0,感谢0,提问0,回答0. :return: 是否是三零用户 :rtype: bool """ return self.upvote_num + self.thank_num + \ self.question_num + self.answer_num == 0
python
def match_many(self, models, results, relation): """ Match the eargerly loaded resuls to their single parents. :param models: The parents :type models: list :param results: The results collection :type results: Collection :param relation: The relation :...
python
def power_up(self): """ power up the HX711 :return: always True :rtype bool """ GPIO.output(self._pd_sck, False) time.sleep(0.01) return True
python
def dict_to_example(dictionary): """Converts a dictionary of string->int to a tf.Example.""" features = {} for k, v in six.iteritems(dictionary): features[k] = tf.train.Feature(int64_list=tf.train.Int64List(value=v)) return tf.train.Example(features=tf.train.Features(feature=features))
java
@Override public PathImpl schemeWalk(String userPath, Map<String,Object> attributes, String filePath, int offset) { int length = filePath.length(); if (length <= offset || filePath.charAt(offset) != '(') return super.schemeWal...
java
@Override public CPDefinitionVirtualSetting fetchByUUID_G(String uuid, long groupId) { return fetchByUUID_G(uuid, groupId, true); }
java
public void setTickMarkColor(final Color COLOR) { if (null == tickMarkColor) { _tickMarkColor = COLOR; fireUpdateEvent(REDRAW_EVENT); } else { tickMarkColor.set(COLOR); } }
python
def prox_hard_plus(X, step, thresh=0): """Hard thresholding with projection onto non-negative numbers """ return prox_plus(prox_hard(X, step, thresh=thresh), step)
python
def _mm_top1(n_items, data, params): """Inner loop of MM algorithm for top1 data.""" weights = exp_transform(params) wins = np.zeros(n_items, dtype=float) denoms = np.zeros(n_items, dtype=float) for winner, losers in data: wins[winner] += 1 val = 1 / (weights.take(losers).sum() + wei...
java
public CreateNotificationResponse createNotification(CreateNotificationRequest request) { checkNotNull(request, "The parameter request should NOT be null."); checkStringNotEmpty(request.getName(), "The parameter name should NOT be null or empty string."); checkStringNotEmpty(req...
java
public static <K> boolean containsAny(Set<K> aSet, K[] arr) { for (K obj : arr) { if (aSet.contains(obj)) { return true; } } return false; }
python
def create_chebyshev_samples(order, dim=1): """ Chebyshev sampling function. Args: order (int): The number of samples to create along each axis. dim (int): The number of dimensions to create samples for. Returns: samples following Chebyshev sampling sche...
python
def transform(self, jam, query=None): '''Transform jam object to make data for this task Parameters ---------- jam : jams.JAMS The jams container object query : string, dict, or callable [optional] An optional query to narrow the elements of `jam.annotat...
python
def combining_successors(state, last_action=()): """ Successors function for finding path of combining F2L pair. """ ((corner, edge), (L, U, F, D, R, B)) = state U_turns = [Formula("U"), Formula("U'"), Formula("U2")] if len(last_action) != 1 else [] R_turns = [Formula("R ...
java
private Map<String, Resource> getClassPathResources(String mimetype, Collection<String> paths) { // If no paths are provided, just return an empty map if (paths == null) return Collections.<String, Resource>emptyMap(); // Add classpath resource for each path provided Map<S...
python
def iri_to_uri(value, normalize=False): """ Encodes a unicode IRI into an ASCII byte string URI :param value: A unicode string of an IRI :param normalize: A bool that controls URI normalization :return: A byte string of the ASCII-encoded URI """ if not isinstance(...
java
protected static int binarySearchGuess(@NotNull final BasePage page, @NotNull final ByteIterable key) { int index = binarySearchGuessUnsafe(page, key); if (index < 0) index = 0; return index; }
java
@NonNull @UiThread public static Router attachRouter(@NonNull Activity activity, @NonNull ViewGroup container, @Nullable Bundle savedInstanceState) { ThreadUtils.ensureMainThread(); LifecycleHandler lifecycleHandler = LifecycleHandler.install(activity); Router router = lifecycleHandler.get...
java
protected EncodedImage getByteBufferBackedEncodedImage( InputStream inputStream, int length) throws IOException { CloseableReference<PooledByteBuffer> ref = null; try { if (length <= 0) { ref = CloseableReference.of(mPooledByteBufferFactory.newByteBuffer(inputStream)); } else { ...
python
def verify(x, t, y, pi, errorOnFail=True): """ Verifies a zero-knowledge proof. @errorOnFail: Raise an exception if the proof does not hold. """ # Unpack the proof p,_,_ = pi # Verify types assertType(x, str) assertType(t, str) assertType(y, G1Element) assertType(p, G2Elemen...
python
def poll(self, id): """Poll with a given id. Parameters ---------- id : int Poll id. Returns ------- an :class:`ApiQuery` of :class:`Poll` Raises ------ :class:`NotFound` If a poll with the requested id doesn't ex...
java
public static mps_upgrade upgrade(nitro_service client, mps_upgrade resource) throws Exception { return ((mps_upgrade[]) resource.perform_operation(client, "upgrade"))[0]; }
python
def RebootInstance(r, instance, reboot_type=None, ignore_secondaries=False, dry_run=False): """ Reboots an instance. @type instance: str @param instance: instance to rebot @type reboot_type: str @param reboot_type: one of: hard, soft, full @type ignore_secondaries: bool ...
python
def path(self, which=None): """Extend ``nailgun.entity_mixins.Entity.path``. The format of the returned path depends on the value of ``which``: logs /containers/<id>/logs power /containers/<id>/power ``super`` is called otherwise. """ i...
python
def stats(args): """ %prog stats infile.gff Collect gene statistics based on gff file. There are some terminology issues here and so normally we call "gene" are actually mRNA, and sometimes "exon" are actually CDS, but they are configurable. Thee numbers are written to text file in four separa...
java
public DescribeComplianceByResourceRequest withComplianceTypes(String... complianceTypes) { if (this.complianceTypes == null) { setComplianceTypes(new com.amazonaws.internal.SdkInternalList<String>(complianceTypes.length)); } for (String ele : complianceTypes) { this.comp...
python
def make_linkcode_resolve(package, url_fmt): """Returns a linkcode_resolve function for the given URL format revision is a git commit reference (hash or name) package is the name of the root module of the package url_fmt is along the lines of ('https://github.com/USER/PROJECT/' ...
java
public FessMessages addErrorsDesignFileIsUnsupportedType(String property) { assertPropertyNotNull(property); add(property, new UserMessage(ERRORS_design_file_is_unsupported_type)); return this; }
python
def token(self): ''' The token used for the request ''' # find the token (cookie or headers) if AUTH_TOKEN_HEADER in self.request.headers: return self.request.headers[AUTH_TOKEN_HEADER] else: return self.get_cookie(AUTH_COOKIE_NAME)
python
def check_unknown_attachment_in_space(confluence, space_key): """ Detect errors in space :param confluence: :param space_key: :return: """ page_ids = get_all_pages_ids(confluence, space_key) print("Start review pages {} in {}".format(len(page_ids), space_key)) for page_id in...
python
def plot_total(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the total gravity disturbance. Usage ----- x.plot_total([tick_interval, xlabel, ylabel, ax, colorbar, cb_ori...
java
@RequestMapping("/person") public final String person( @RequestParam(value = "id", required = false, defaultValue = "I0") final String idString, @RequestParam(value = "db", required = false, defaultValue = "schoeller") final Str...
java
public void reset() { while (holes != null) { holes = freePointBag(holes); } contour.clear(); holes = null; }
python
def handle_truncated_response(callback, params, entities): """ Handle truncated responses :param callback: :param params: :param entities: :return: """ results = {} for entity in entities: results[entity] = [] while True: try: marker_found = False ...
java
@Override @SuppressWarnings("unchecked") @Scope(DocScope.IO) public <T> T projectDOMNode(final Node documentOrElement, final Class<T> projectionInterface) { ensureIsValidProjectionInterface(projectionInterface); if (documentOrElement == null) { throw new IllegalArgumentException...
python
def do_labels_update(self, info, labels): """Updates a dictionary of labels using the assigned update_op_func Args: info (:class:`endpoints_management.control.report_request.Info`): the info instance to update labels (dict[string[string]]): the labels dictionary ...
python
def start_depth_socket(self, symbol, callback, depth=None): """Start a websocket for symbol market depth returning either a diff or a partial book https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#partial-book-depth-streams :param symbol: required ...
java
public GetLifecyclePolicyPreviewResult withPreviewResults(LifecyclePolicyPreviewResult... previewResults) { if (this.previewResults == null) { setPreviewResults(new java.util.ArrayList<LifecyclePolicyPreviewResult>(previewResults.length)); } for (LifecyclePolicyPreviewResult ele : pr...
python
def dump_pk(obj, abspath, pk_protocol=pk_protocol, replace=False, compress=False, enable_verbose=True): """Dump Picklable Python Object to file. Provides multiple choice to customize the behavior. :param obj: Picklable Python Object. :param abspath: ``save as`` path, file exten...
java
public boolean compare(Object object) { if (!(object instanceof IChemObject)) { return false; } ChemObject chemObj = (ChemObject) object; return Objects.equal(identifier, chemObj.identifier); }
python
def set_title(self, msg): """ Set first header line text """ self.s.move(0, 0) self.overwrite_line(msg, curses.A_REVERSE)
python
def find_dimension_by_name(self, dim_name): """the method searching dimension with a given name""" for dim in self.dimensions: if is_equal_strings_ignore_case(dim.name, dim_name): return dim return None
java
static ResourceLocator.Request buildChallengeRequest(ResourceLocator.Session session, String symbol) { // The "options" part causes the cookie to be set. // Other path endings may also work, // but there has to be something after the symbol return session.request().host(FINANCE_YAHOO_COM...
python
def load(*args, **kwargs): """Load an numpy.ndarray from a file stream. This works exactly like the usual `json.load()` function, but it uses our custom deserializer. """ kwargs.update(dict(object_hook=json_numpy_obj_hook)) return _json.load(*args, **kwargs)
python
def find_all(self, locator, search_object=None, force_find=False): ''' Find all elements matching locator @type locator: webdriverwrapper.support.locator.Locator @param locator: Locator object describing @rtype: list[WebElementWrapper] @...
java
public void save(final SecretKey key) throws IOException { final File keyFile = getKeyPath(key); keyFile.getParentFile().mkdirs(); // make directories if they do not exist try (OutputStream fos = Files.newOutputStream(keyFile.toPath()); ObjectOutputStream oout = new ObjectOutputStre...
java
public ImageSource toFastBitmap() { OneBandSource l = new OneBandSource(width, height); PowerSpectrum(); double max = Math.log(PowerMax + 1.0); double scale = 1.0; if (scaleValue > 0) scale = scaleValue / max; for (int i = 0; i < height; i++) { for ...
python
def backup(path, name=None): """Start a Backup run""" from PyHardLinkBackup.phlb.phlb_main import backup backup(path, name)
python
def cifar10_patches(data_set='cifar-10'): """The Candian Institute for Advanced Research 10 image data set. Code for loading in this data is taken from this Boris Babenko's blog post, original code available here: http://bbabenko.tumblr.com/post/86756017649/learning-low-level-vision-feautres-in-10-lines-of-code""" ...
java
public void addClassConstant(Content summariesTree, Content classConstantTree) { if (configuration.allowTag(HtmlTag.SECTION)) { summaryTree.addContent(classConstantTree); } else { summariesTree.addContent(classConstantTree); } }
java
public String toJSON() { StringBuffer result = new StringBuffer(); result.append("{\n"); for (Entry<String, List<String>> simpleEntry : m_simpleAttributes.entrySet()) { result.append("\"").append(simpleEntry.getKey()).append("\"").append(": [\n"); boolean firstValu...
java
public <T> List<T> querySingleColumnTypedResults(String sql, String[] args) { @SuppressWarnings("unchecked") List<T> result = (List<T>) querySingleColumnResults(sql, args); return result; }
java
public Boolean getWicketDebugToolbar() { if(getDevelopment()) { return wicketDebugToolbar != null ? wicketDebugToolbar : true; } else { return wicketDebugToolbar != null ? wicketDebugToolbar : false; } }
python
def _get_value(first, second): """ 数据转化 :param first: :param second: :return: >>> _get_value(1,'2') 2 >>> _get_value([1,2],[2,3]) [1, 2, 3] """ if isinstance(first, list) and isinstance(second, list): return list(set(first).union(set(second))) elif isinstance(fir...
python
def _get_spec(cls, fullname, path, target=None): """Find the loader or namespace_path for this module/package name.""" # If this ends up being a namespace package, namespace_path is # the list of paths that will become its __path__ namespace_path = [] for entry in path: ...
python
def _interpolate_p(p, r, v): """ interpolates p based on the values in the A table for the scalar value of r and the scalar value of v """ # interpolate p (v should be in table) # if .5 < p < .75 use linear interpolation in q # if p > .75 use quadratic interpolation in log(y + r/v) # by...
java
public PrivateKey get(KeyStoreChooser keyStoreChooser, PrivateKeyChooserByAlias privateKeyChooserByAlias) { CacheKey cacheKey = new CacheKey(keyStoreChooser.getKeyStoreName(), privateKeyChooserByAlias.getAlias()); PrivateKey retrievedPrivateKey = cache.get(cacheKey); if (retrievedPrivateKey != ...
python
def upload_token( self, bucket, key=None, expires=3600, policy=None, strict_policy=True): """生成上传凭证 Args: bucket: 上传的空间名 key: 上传的文件名,默认为空 expires: 上传凭证的过期时间,默认为3600s policy: 上传策...
python
def _verify_dict(self, conf): """ Check that the configuration contains all necessary keys. :type conf: dict :rtype: None :raise SATOSAConfigurationError: if the configuration is incorrect :param conf: config to verify :return: None """ if not co...
python
def with_(self, replacement): """Provide replacement for string "needles". :param replacement: Target replacement for needles given in constructor :return: The :class:`Replacement` object :raise TypeError: If ``replacement`` is not a string :raise ReplacementError: If replaceme...
python
def get_more(self, show=True, proxy=None, timeout=0): """ Calls get_querymore() Is for convenience. You like. """ return self.get_querymore(show, proxy, timeout)
java
public void writeTo(Writer target, boolean flushTarget, boolean emptyAfter) throws IOException { //if (target instanceof GrailsWrappedWriter) { // target = ((GrailsWrappedWriter)target).unwrap(); //} if (target instanceof StreamCharBufferWriter) { i...
python
def save_image(image, destination=None, filename=None, **options): """ Save a PIL image. """ if destination is None: destination = BytesIO() filename = filename or '' # Ensure plugins are fully loaded so that Image.EXTENSION is populated. Image.init() format = Image.EXTENSION.get...
java
@XmlElementDecl(namespace = "http://schema.intuit.com/finance/v3", name = "Term", substitutionHeadNamespace = "http://schema.intuit.com/finance/v3", substitutionHeadName = "IntuitObject") public JAXBElement<Term> createTerm(Term value) { return new JAXBElement<Term>(_Term_QNAME, Term.class, null, value); ...
python
def execution_order(self, refcounts): """ Return a topologically-sorted iterator over the terms in ``self`` which need to be computed. """ return iter(nx.topological_sort( self.graph.subgraph( {term for term, refcount in refcounts.items() if refcount >...
java
public static long getWeekStartTime(final long time) { final Calendar start = Calendar.getInstance(); start.setFirstDayOfWeek(Calendar.MONDAY); start.setTimeInMillis(time); start.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); start.set(Calendar.HOUR, 0); start.set(Calendar.M...
java
private String getRowLineBuf(int colCount, List<Integer> colMaxLenList, String[][] data) { StringBuilder rowBuilder = new StringBuilder(); int colWidth = 0; for (int i = 0; i < colCount; i++) { colWidth = colMaxLenList.get(i) + 3; for (int j = 0; j < colWidth; j++) { if (j ...
java
public void deleteObjects(Collection objects) { for (Iterator iterator = objects.iterator(); iterator.hasNext();) { getDatabase().deletePersistent(iterator.next()); } }
python
def _prepRESearchStr(matchStr, wordInitial='ok', wordFinal='ok', spanSyllable='ok', stressedSyllable='ok'): ''' Prepares a user's RE string for a search ''' # Protect sounds that are two characters # After this we can assume that each character represents a sound # (We'...
java
public List<String> getPossiblePaths(int maxDepth) { if (allDissectors.isEmpty()) { return Collections.emptyList(); // nothing to do. } try { assembleDissectors(); } catch (MissingDissectorsException | InvalidDissectorException e) { // Simply swallow ...
python
def register_regex_entity(self, regex_str, domain=0): """ A regular expression making use of python named group expressions. Example: (?P<Artist>.*) Args: regex_str(str): a string representing a regular expression as defined above domain(str): a string represent...
java
public int getCurrentMethodOrdinal(int overrideId, int pathId, String clientUUID, String[] filters) throws Exception { int currentOrdinal = 0; List<EnabledEndpoint> enabledEndpoints = getEnabledEndpoints(pathId, clientUUID, filters); for (EnabledEndpoint enabledEndpoint : enabledEndpoints) { ...
python
def update_pypsa_generator_import(network): """ Translate graph based grid representation to PyPSA Network For details from a user perspective see API documentation of :meth:`~.grid.network.EDisGo.analyze` of the API class :class:`~.grid.network.EDisGo`. Translating eDisGo's grid topology to P...