language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def context_chunk(self, context, j): """ Retrieve the tokens in the ``j``th chunk of context ``context``. Parameters ---------- context : str Context name. j : int Index of a context chunk. Returns ------- chunk : list ...
java
private static Date parseUsingMask(final String[] masks, String sDate, final Locale locale) { if (sDate != null) { sDate = sDate.trim(); } ParsePosition pp = null; Date d = null; for (int i = 0; d == null && i < masks.length; i++) { final DateFormat df = n...
python
def get_mnc(self, ip): ''' Get mnc ''' rec = self.get_all(ip) return rec and rec.mnc
java
public List<CmsResourceTypeConfig> getResourceTypes() { List<CmsResourceTypeConfig> result = internalGetResourceTypes(true); for (CmsResourceTypeConfig config : result) { config.initialize(getCms()); } return result; }
java
@NonNull public static <T> T nonNull(@Nullable T obj) { if (obj == null) { throw new IllegalArgumentException("encountered illegal null value"); } return obj; }
java
RangeSet getConditions() { RangeSet is = new RangeSet(); for (CharRange ic : transitions.keySet()) { if (ic != null) { is.add(ic); } } return is; }
java
public static EnumSet<KeyUsage> getSetOfKeyUsage(org.bouncycastle.asn1.x509.KeyUsage keyUsage) { if (keyUsage == null) { return null; } Collection<KeyUsage> usages = new ArrayList<KeyUsage>(); for (KeyUsage usage : KeyUsage.values()) { if ((((DERBitString) k...
java
public static String stringFor(int n) { switch (n) { case CUDA_R_16F : return "CUDA_R_16F"; case CUDA_C_16F : return "CUDA_C_16F"; case CUDA_R_32F : return "CUDA_R_32F"; case CUDA_C_32F : return "CUDA_C_32F"; case CUDA_R_64F : retur...
java
public void setLemma(String v) { if (WordForm_Type.featOkTst && ((WordForm_Type)jcasType).casFeat_lemma == null) jcasType.jcas.throwFeatMissing("lemma", "com.digitalpebble.rasp.WordForm"); jcasType.ll_cas.ll_setStringValue(addr, ((WordForm_Type)jcasType).casFeatCode_lemma, v);}
java
@Override public void initialize(InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException { try { FileSplit fSplit = (FileSplit)split; // Initialize start and end of split start = fSplit.getStart(); end = start + fSplit.getLength(); final Path file = fSplit.getPath(); c...
python
def WriteClientMetadata(self, client_id, certificate=None, fleetspeak_enabled=None, first_seen=None, last_ping=None, last_clock=None, last...
java
public static String message(String key, Locale locale, Object... params) { return getMessage(key, locale, params); }
python
def logical_chassis_fwdl_sanity_output_cluster_output_rbridge_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") logical_chassis_fwdl_sanity = ET.Element("logical_chassis_fwdl_sanity") config = logical_chassis_fwdl_sanity output = ET.SubElement(l...
java
protected Connection getReadConnection() throws CpoException { Connection connection; try { if (!(invalidReadConnection_)) { connection = getReadDataSource().getConnection(); } else { connection = getWriteDataSource().getConnection(); } connection.setAutoCommit(false); ...
python
def get_languages(self, target_language=None): """Get list of supported languages for translation. Response See https://cloud.google.com/translate/docs/discovering-supported-languages :type target_language: str :param target_language: (Optional) The language used to lo...
python
def is_equivalent(self, callback, details_filter=None): """Check if the callback provided is the same as the internal one. :param callback: callback used for comparison :param details_filter: callback used for comparison :returns: false if not the same callback, otherwise true :...
python
def shap_values(self, X, **kwargs): """ Estimate the SHAP values for a set of samples. Parameters ---------- X : numpy.array or pandas.DataFrame A matrix of samples (# samples x # features) on which to explain the model's output. Returns ------- For ...
java
public static void setGreetingMessage(List<Greeting> message) { SetGreetingTextRequest request = new SetGreetingTextRequest(message); FbBotMillNetworkController.postMessengerProfile(request); }
java
public double[][] solve(double[][] B) { if (B.length != m) { throw new IllegalArgumentException("Matrix row dimensions must agree."); } if (!this.isFullRank()) { throw new RuntimeException("Matrix is rank deficient."); } // Copy right hand side in...
java
public ApplicationInner beginCreate(String resourceGroupName, String clusterName, String applicationName, ApplicationInner parameters) { return beginCreateWithServiceResponseAsync(resourceGroupName, clusterName, applicationName, parameters).toBlocking().single().body(); }
python
def read_multireg_file(f, title=None): """ Some REG files have multiple "sections" with different data. This parses each chunk out of such a file (e.g. LCDIAG.REG) """ f.seek(0x26) nparts = struct.unpack('<H', f.read(2))[0] foff = 0x2D if title is None: data = [] for _ in...
python
def list_sqs(region, filter_by_kwargs): """List all SQS Queues.""" conn = boto.sqs.connect_to_region(region) queues = conn.get_all_queues() return lookup(queues, filter_by=filter_by_kwargs)
python
def call(self, func, *args, **kwargs): """ Like :meth:`mitogen.parent.CallChain.call`, but log timings. """ t0 = time.time() try: recv = self.call_async(func, *args, **kwargs) return self._rethrow(recv) finally: LOG.debug('Call took %d ...
python
def add_string_pairs_from_button_element(xib_file, results, button, special_ui_components_prefix): """ Adds strings pairs from a button xib element. Args: xib_file (str): Path to the xib file. results (list): The list to add the results to. button(element): The button element from the x...
python
def elem_type(self): """ :returns: "select"|"radio"|"checkbox" """ if not hasattr(self, "_elem_type"): self._elem_type = get_elem_type(self.elem) return self._elem_type
python
def verifychain(self, anchors, untrusted=None): """ Perform verification of certificate chains for that certificate. The behavior of verifychain method is mapped (and also based) on openssl verify userland tool (man 1 verify). A list of anchors is required. untrusted parameter ca...
python
def _ProgressMeterUpdate(bar, value, text_elem, *args): ''' Update the progress meter for a form :param form: class ProgressBar :param value: int :return: True if not cancelled, OK....False if Error ''' global _my_windows if bar == None: return False if bar.BarExpired: return False ...
python
def set_alpha_value(self, value): ''' setter Learning rate. ''' if isinstance(value, float) is False: raise TypeError("The type of __alpha_value must be float.") self.__alpha_value = value
java
public static void gbk_presel( float best_gain[], /* input : [0] unquantized pitch gain [1] unquantized code gain */ IntegerPointer cand1, /* output: index of best 1st stage vector */ IntegerPointer cand2, /* output: index of best 2nd stage vect...
java
public DbInfo info() { return client.couchDbClient.get(new DatabaseURIHelper(db.getDBUri()).getDatabaseUri(), DbInfo.class); }
python
def get_comment_query_session_for_book(self, book_id, proxy): """Gets the ``OsidSession`` associated with the comment query service for the given book. arg: book_id (osid.id.Id): the ``Id`` of the ``Book`` arg: proxy (osid.proxy.Proxy): a proxy return: (osid.commenting.CommentQuer...
python
def _prepare_transition(self, is_on=None, brightness=None, color=None): """ Perform pre-transition tasks and construct the destination state. :param is_on: The on-off state to transition to. :param brightness: The brightness to transition to (0.0-1.0). :param color: The color to...
python
def main(miz_path): """ Artifact from earlier development """ from emiz.miz import Miz with Miz(miz_path) as m: mis = m.mission result = defaultdict(dict) for unit in mis.units: airport, spot = unit.group_name.split('#') spot = int(spot) # print(airport, int(...
java
public File createArchive() throws IOException, ZipException { File tmpFile = File.createTempFile("dw-data", ".zip"); try { tmpFile.delete(); ZipFile zipFile = new ZipFile(tmpFile.getAbsoluteFile()); ZipParameters parameters = new ZipParameters(); parameters.setCompressionLevel(Zip4jConstants.DEFLATE_L...
python
def interlink_translated_content(generator): '''Make translations link to the native locations for generators that may contain translated content ''' inspector = GeneratorInspector(generator) for content in inspector.all_contents(): interlink_translations(content)
python
def _fieldnames_to_colnames(model_cls, fieldnames): """Get the names of columns referenced by the given model fields.""" get_field = model_cls._meta.get_field fields = map(get_field, fieldnames) return {f.column for f in fields}
python
def query_metrics_data(self, metric_names, objects): """Queries collected metrics data for a set of objects. The data itself and related metric information are returned in seven parallel and one flattened array of arrays. Elements of returnMetricNames, returnObjects, returnUnits...
java
public void marshall(DescribeClustersRequest describeClustersRequest, ProtocolMarshaller protocolMarshaller) { if (describeClustersRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(describeCl...
java
public Pair<int[][][][], int[][]> documentsToDataAndLabels(Collection<List<IN>> documents) { // first index is the number of the document // second index is position in the document also the index of the // clique/factor table // third index is the number of elements in the clique/window these fea...
java
public RequestParameterBuilder paramJson(String name, Object value, String type) throws UnsupportedEncodingException { String encodedJsonValue = encodeJson(value, type); if (added || originalUrl.contains("?")) { buffer.append("&"); } else { buffer.append("?"); ...
python
def save(self, dolist=0): """Return .par format string for this parameter If dolist is set, returns fields as a list of strings. Default is to return a single string appropriate for writing to a file. """ quoted = not dolist array_size = 1 for d in self.shape: ...
python
def update_git_repository(self, folder, git_repository): """Updates git remote for the managed theme folder if has changed. :param git_repository: git url of the theme folder :param folder: path of the git managed theme folder """ # load repo object from path repo = git...
java
private Optional<String> process(final String path, Function<String, String> func) { String workPath = path; if (workPath == null) { throw new IllegalArgumentException("Given String must not be null!"); } if (workPath.charAt(0) != PATH_SEPARATOR) { workPath = PATH_SEPARATOR + workPath; } workPath = fu...
python
def collapse_pane(self, side): """ Toggle collapsing the left or right panes. """ # TODO: this is too tied to one configuration, need to figure # out how to generalize this hsplit = self.w['hpnl'] sizes = hsplit.get_sizes() lsize, msize, rsize = sizes ...
python
def get_vmotion_enabled(host, username, password, protocol=None, port=None, host_names=None): ''' Get the VMotion enabled status for a given host or a list of host_names. Returns ``True`` if VMotion is enabled, ``False`` if it is not enabled. host The location of the host. username ...
python
def vertex_indices_in_segments(self, segments, ret_face_indices=False): ''' Given a list of segment names, return an array of vertex indices for all the vertices in those faces. Args: segments: a list of segment names, ret_face_indices: if it is `True`, returns f...
python
def find_one_node(self, *keys, value, decend=True): """Find a node on the branch of the instance with a `keys=data` item in the `data` dict. Nested values are accessed by specifying the keys in sequence. e.g. `node.get_data("country", "city")` would access `node.data["country"...
java
public static int downSampleSize( int length , int squareWidth ) { int ret = length/squareWidth; if( length%squareWidth != 0 ) ret++; return ret; }
python
def update(self, back=None): ''' Update all of the enabled fileserver backends which support the update function, or ''' back = self.backends(back) for fsb in back: fstr = '{0}.update'.format(fsb) if fstr in self.servers: log.debug(...
java
private static void validateForCurrentMode(HttpMessage request) throws ApiException { if (!isValidForCurrentMode(request.getRequestHeader().getURI())) { throw new ApiException(ApiException.Type.MODE_VIOLATION); } }
python
def get_generalised_coordinates(self, lons, lats): """ Transforms the site positions into the generalised coordinate form described by Spudich and Chiou (2015) for the multi-rupture and/or discordant case Spudich, Paul and Chiou, Brian (2015) Strike-parallel and strike-normal ...
python
def calculate_num_slices_per_axis(num_slices_per_axis, num_slices, max_slices_per_axis=None): """ Returns a :obj:`numpy.ndarray` (:samp:`return_array` say) where non-positive elements of the :samp:`{num_slices_per_axis}` sequence have been replaced with positive integer values such that :samp:`numpy.pro...
java
public static <T extends ImageGray<T>, II extends ImageGray<II>> DetectDescribePoint<T,BrightFeature> surfColorFast( @Nullable ConfigFastHessian configDetector , @Nullable ConfigSurfDescribe.Speed configDesc, @Nullable ConfigAverageIntegral configOrientation, ImageType<T> imag...
python
def normalize_r_value(self): ''' Normalize r-value. Override. This method is called in each learning steps. For example: self.r_df = self.r_df.r_value / self.r_df.r_value.sum() ''' if self.r_df is not None and self.r_df.shape[0]: # z-sco...
python
def read_csv(filepath): """ Read a CSV into a list of dictionarys. The first line of the CSV determines the keys of the dictionary. Parameters ---------- filepath : string Returns ------- list of dictionaries """ symbols = [] with open(filepath, 'rb') as csvfile: ...
java
private synchronized void doResourceRequest(final ResourceRequestEvent resourceRequestEvent) { int tasksToLaunchCounter = resourceRequestEvent.getResourceCount(); for (final Offer offer : this.offers.values()) { final int cpuSlots = getCpu(offer) / resourceRequestEvent.getVirtualCores().get(); fina...
python
def make_process_node(self, process): """Fill the content of process definiton node. :param dict process: process data as given from yaml.load function :return: process node """ name = process['name'] slug = process['slug'] typ = process['type'] version ...
java
public Table createTable(String datasetName, String tableName, String fieldName) { // [START bigquery_create_table] TableId tableId = TableId.of(datasetName, tableName); // Table field definition Field field = Field.of(fieldName, LegacySQLTypeName.STRING); // Table schema definition Schema schem...
java
public static JavaRDD<LabeledPoint> fromDataSet(JavaRDD<DataSet> data, boolean preCache) { if (preCache && !data.getStorageLevel().useMemory()) { data.cache(); } return data.map(new Function<DataSet, LabeledPoint>() { @Override public LabeledPoint call(DataSet...
python
def http_request(cls, url, method='GET', body=None, headers=None): """Make an HTTP request with the given method to the given URL, returning the resulting `http_client.HTTPResponse` instance. If the `body` argument is a `Resource` instance, it is serialized to XML by calling its `to_ele...
python
def read(self, size=None): # type: (Optional[int]) -> bytes ''' A method to read and return up to size bytes. Parameters: size - Optional parameter to read size number of bytes; if None or negative, all remaining bytes in the file will be read Returns: ...
python
def search(cls, term, weights=None, with_score=False, score_alias='score', explicit_ordering=False): """Full-text search using selected `term`.""" return cls.search_bm25( FTS5Model.clean_query(term), weights, with_score, score_alias, ...
java
public void drawText(Graphics2D g) { // We don't want to corrupt the graphics environs with our // affine transforms! Graphics2D g2 = (Graphics2D) g.create(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.transform(affineToText); // What about the text labe...
python
def cannot_convert(self, node, reason=None): """Warn the user that a given chunk of code is not valid Python 3, but that it cannot be converted automatically. First argument is the top-level node for the code in question. Optional second argument is why it can't be converted. ""...
java
@Override public List<CommerceWishList> findByG_U_D(long groupId, long userId, boolean defaultWishList) { return findByG_U_D(groupId, userId, defaultWishList, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); }
python
async def get_me(self, input_peer=False): """ Gets "me" (the self user) which is currently authenticated, or None if the request fails (hence, not authenticated). Args: input_peer (`bool`, optional): Whether to return the :tl:`InputPeerUser` version or the no...
java
public ThriftClient<T> getClient() throws ThriftException { try { return pool.borrowObject(); } catch (Exception e) { if (e instanceof ThriftException) { throw (ThriftException) e; } throw new ThriftException("Get client from pool failed.",...
java
@Override public void setValue(final double VALUE) { if (isEnabled()) { this.value100 = (VALUE % 1000) / 100; this.value1000 = (VALUE % 10000) / 100; this.value10000 = (VALUE % 100000) / 100; if (isValueCoupled()) { setLcdValue(VALUE); ...
java
protected static Type getTypeReferenceForName(String className, String... genericTypes) { String referenceString = getTypeDescriptor(className, genericTypes); return Type.getType(referenceString); }
python
def from_file_url(url): """ Convert from file:// url to file path """ if url.startswith('file://'): url = url[len('file://'):].replace('/', os.path.sep) return url
java
public static String getMessage(String key, Object... params) { return getPm().message(key, params); }
java
public void marshall(ProvisionedProductDetail provisionedProductDetail, ProtocolMarshaller protocolMarshaller) { if (provisionedProductDetail == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(provisi...
python
def add_dependency(self, from_task_name, to_task_name): """ Add a dependency between two tasks. """ logger.debug('Adding dependency from {0} to {1}'.format(from_task_name, to_task_name)) if not self.state.allow_change_graph: raise DagobahError("job's graph is immutable in its curren...
python
def sanitize_command_options(options): """ Sanitizes command options. """ multiples = [ 'badges', 'exclude_badges', ] for option in multiples: if options.get(option): value = options[option] if value: options[option] = [v for v in ...
java
private String generateTypeKey(final Object object, final KeyGenerator typeGenerator) { String objectKey = null; Method method = null; try { method = object.getClass().getMethod(typeGenerator.value()); objectKey = (String) method.invoke(object); } catch (fin...
python
def get_accessibility(self, plugin_override=True): """ Return the AccessibleTime object associated with the accessibility of this course """ vals = self._hook_manager.call_hook('course_accessibility', course=self, default=self._accessible) return vals[0] if len(vals) and plugin_override else sel...
python
def fit(self, X, y=None): """ Compute agglomerative clustering. Parameters ---------- X : array-like, shape=(n_samples, n_features) Returns ------- self """ if self.max_landmarks is not None: if self.n_clusters > self.n_landm...
python
def _port_bound(self, port_id, network_id, network_type, physical_network, segmentation_id, port_security_enabled, set_port_sriov): """Bind the port to the recived network.""" super(HNVAgent, self)._port_bound(port_id, network_id, network_type, ...
java
public boolean getBoolean() { byte result = buffer.getByte(index + offset); index += Bits.BYTE_SIZE_IN_BYTES; return result != 0; }
python
def zip_hash(cls, zf, prefix=''): """Return the hash of the contents of a zipfile, comparable with a cls.dir_hash.""" prefix_length = len(prefix) names = sorted(name[prefix_length:] for name in zf.namelist() if name.startswith(prefix) and not name.endswith('.pyc') and not name.endswith('/')) def...
java
@Override public void execute() throws MojoExecutionException, MojoFailureException { // Prepare an execution. Execution execution = new FailOnErrorExecution(); execution.setAlgorithms( Arrays.asList( Constants.SUPPORTED_ALGORITHMS ) ); execution.addFile( new ChecksumFile...
java
public static OrientationHelperEx createVerticalHelper(ExposeLinearLayoutManagerEx layoutManager) { return new OrientationHelperEx(layoutManager) { @Override public int getEndAfterPadding() { return mLayoutManager.getHeight() - mLayoutManager.getPaddingBottom(); ...
python
def knx_to_time(knxdata): """Converts a KNX time to a tuple of a time object and the day of week""" if len(knxdata) != 3: raise KNXException("Can only convert a 3 Byte object to time") dow = knxdata[0] >> 5 res = time(knxdata[0] & 0x1f, knxdata[1], knxdata[2]) return [res, dow]
java
public static void setDrawableTint(@NonNull Drawable drawable, @ColorInt int color) { DrawableCompat.setTint(DrawableCompat.wrap(drawable.mutate()), color); }
python
def initial_contact(self, enable_ssh=True, time_zone=None, keyboard=None, install_on_server=None, filename=None, as_base64=False): """ Allows to save the initial contact for for the specified node :p...
java
@Override public EClass getIfcStackTerminalType() { if (ifcStackTerminalTypeEClass == null) { ifcStackTerminalTypeEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(623); } return ifcStackTerminalTypeEClass; }
java
public static String getDateTimeShort(long time) { return getDateTime(new Date(time), DateFormat.SHORT, CmsLocaleManager.getDefaultLocale()); }
python
def split_sentences(self, text): """ Split input text into sentences that match CoreNLP's default format, but are not yet processed. :param text: The text of the parent paragraph of the sentences :return: """ if self.model.has_pipe("sentence_boundary_detector"):...
python
def on_message(self, name): """ Decorator for message listener callback functions. .. tip:: This is the most elegant way to define message listener callback functions. Use :py:func:`add_message_listener` only if you need to be able to :py:func:`remove the li...
java
public static String dequoteFull(String str, char quote) { if (str == null) { return null; } return dequoteFull(str, 0, str.length(), quote); }
java
public static SignatureValidationFilter buildSignatureValidationFilter(final Resource signatureResourceLocation) throws Exception { if (!ResourceUtils.doesResourceExist(signatureResourceLocation)) { LOGGER.warn("Resource [{}] cannot be located", signatureResourceLocation); return null; ...
java
public void put(long key, T element) { Entry<T> entry = new Entry<T>(key, element); elements.add(entry); this.numElements++; fileElement(entry, true); }
python
def scrape_document(self, item_session: ItemSession): '''Process document for links.''' self.event_dispatcher.notify( PluginFunctions.get_urls, item_session ) if not self._document_scraper: return demux_info = self._document_scraper.scrape_info( ...
java
public ScheduledFuture<?> schedule() { synchronized (this.triggerContextMonitor) { this.scheduledExecutionTime = this.trigger.nextExecutionTime(this.triggerContext); if (this.scheduledExecutionTime == null) { return null; } long initialDelay = this...
java
public RadiusSettings withRadiusServers(String... radiusServers) { if (this.radiusServers == null) { setRadiusServers(new com.amazonaws.internal.SdkInternalList<String>(radiusServers.length)); } for (String ele : radiusServers) { this.radiusServers.add(ele); } ...
python
def edit_preferences(self, resource): """Edit preferences in /usr/cdrouter-data/etc/config.yml. :param resource: :class:`system.Preferences <system.Preferences>` object :return: :class:`system.Preferences <system.Preferences>` object :rtype: system.Preferences """ schema...
python
def get_urls(self): """ Add the entries view to urls. """ urls = super(FormAdmin, self).get_urls() extra_urls = [ re_path("^(?P<form_id>\d+)/entries/$", self.admin_site.admin_view(self.entries_view), name="form_entries"), re...
java
void dispatchSync(DispatchQueue networkQueue) { long requestStartTime = System.currentTimeMillis(); try { sendRequestSync(); } catch (NetworkUnavailableException e) { responseCode = -1; // indicates failure errorMessage = e.getMessage(); ApptentiveLog.w(NETWORK, e.getMessage()); ApptentiveLog.w(NE...
java
public void setListeners(@NonNull Collection<TrainingListener> listeners) { this.listeners.clear(); this.listeners.addAll(listeners); if (trainingMaster != null) trainingMaster.setListeners(this.listeners); }
java
public byte[] toByteArray() throws IOException { DerOutputStream out = new DerOutputStream(); encode(out); data.reset(); return out.toByteArray(); }