language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public TSMeta parseTSMetaV1() { final String json = query.getContent(); if (json == null || json.isEmpty()) { throw new BadRequestException(HttpResponseStatus.BAD_REQUEST, "Missing message content", "Supply valid JSON formatted data in the body of your request"); } try { ...
python
def get(self, name, typ): """ Gets a counter specified by its name. It counter does not exist or its type doesn't match the specified type it creates a new one. :param name: a counter name to retrieve. :param typ: a counter type. :return: an existing or newly c...
python
def _populate_inception_bottlenecks(scope): """Add Inception bottlenecks and their pre-Relu versions to the graph.""" graph = tf.get_default_graph() for op in graph.get_operations(): if op.name.startswith(scope+'/') and 'Concat' in op.type: name = op.name.split('/')[1] pre_relus = [] for tow...
python
def id_fix(value): """ fix @prefix values for ttl """ if value.startswith('KSC_M'): pass else: value = value.replace(':','_') if value.startswith('ERO') or value.startswith('OBI') or value.startswith('GO') or value.startswith('UBERON') or value.startswith('IAO'): value = ...
java
private byte[] writeExtendingClass(Class<?> type, String className) { String clazz = ClassUtils.classNameToInternalClassName(className); ByteArrayOutputStream bIn = new ByteArrayOutputStream(1000); // 1000 should be large enough to fit the entire class try(DataOutputStream in = new DataOutputStream(...
python
def ss(inlist): """ Squares each value in the passed list, adds up these squares and returns the result. Usage: lss(inlist) """ ss = 0 for item in inlist: ss = ss + item * item return ss
python
def _setup_param_widgets(self): """Creates the parameter entry widgets and binds them to methods""" for parameter in self.csv_params: pname, ptype, plabel, phelp = parameter label = wx.StaticText(self.parent, -1, plabel) widget = self.type2widget[ptype](self.parent)...
java
public static LeaderConnectionInfo retrieveLeaderConnectionInfo( LeaderRetrievalService leaderRetrievalService, Time timeout) throws LeaderRetrievalException { return retrieveLeaderConnectionInfo(leaderRetrievalService, FutureUtils.toFiniteDuration(timeout)); }
java
public CrosstabBuilder addRow(String title, String property, String className, boolean showTotal, Style headerStyle, Style totalStyle, Style totalHeaderStyle) { DJCrosstabRow row = new CrosstabRowBuilder() .setProperty(property,className) .setShowTotals(showTotal) .setTitle(title) .setHeaderStyle(hea...
python
def load(self, schema_file: Union[str, TextIO], schema_location: Optional[str]=None) -> ShExJ.Schema: """ Load a ShEx Schema from schema_location :param schema_file: name or file-like object to deserialize :param schema_location: URL or file name of schema. Used to create the base_location ...
java
@SuppressWarnings("unchecked") protected T normalizedToValue(double normalized) { double v = absoluteMinValuePrim + normalized * (absoluteMaxValuePrim - absoluteMinValuePrim); // TODO parameterize this rounding to allow variable decimal points return (T) numberType.toNumber(Math.round(v * 10...
java
protected void addEquiJoinColumn( QueryContext context, PlanNode node, Column joinColumn ) { if (node.getSelectors().contains(joinColumn.selectorName())) { // Get the existing projected columns ... List<Column> c...
python
def show_tracebacks(self): """ Show tracebacks """ if self.broker.tracebacks: print(file=self.stream) print("Tracebacks:", file=self.stream) for t in self.broker.tracebacks.values(): print(t, file=self.stream)
java
protected String getJSIncludeFile(String fileName) { StringBuffer result = new StringBuffer(8); result.append("<script type=\"text/javascript\" src=\""); result.append(fileName); result.append("\"></script>"); return result.toString(); }
python
def load(fh, encoding=None, is_verbose=False): """load a pickle, with a provided encoding if compat is True: fake the old class hierarchy if it works, then return the new type objects Parameters ---------- fh : a filelike object encoding : an optional encoding is_verbose : sh...
java
public static ViewDefinition of(String query, List<UserDefinedFunction> functions) { return newBuilder(query, functions).build(); }
java
public Observable<ServiceResponse<NetworkSettingsInner>> getNetworkSettingsWithServiceResponseAsync(String deviceName, String resourceGroupName) { if (deviceName == null) { throw new IllegalArgumentException("Parameter deviceName is required and cannot be null."); } if (this.client.s...
java
public StateMachine<T> withTransition(T from, T to, T... moreTo) { transitions.put(from, EnumSet.of(to, moreTo)); return this; }
java
private static List<CopyPath> expandDirectories(FileSystem fs, List<Path> paths, Path dstPath) throws IOException { List<CopyPath> newList = new ArrayList<CopyPath>(); FileSystem dstFs = dstPath.getFileSystem(defaultConf); boolean isDstFile = false; try { FileStatus dstPathStatus = ds...
python
def dataset_list(self): '''Subcommand of dataset for listing available datasets''' # Initialize the prepare subcommand's argparser parser = argparse.ArgumentParser(description='Preprocess a raw dialogue corpus into a dsrt dataset') self.init_dataset_list_args(parser) # Parse th...
python
def get_t(self): """Returns the top border of the cell""" cell_above = CellBorders(self.cell_attributes, *self.cell.get_above_key_rect()) return cell_above.get_b()
java
private static List<Path> expandMultiAppInputDirs(List<Path> input) { List<Path> expanded = new LinkedList<>(); for (Path path : input) { if (Files.isRegularFile(path)) { expanded.add(path); continue; } if (!File...
python
def get_request_handler_chain(self, handler_input): # type: (Input) -> Union[GenericRequestHandlerChain, None] """Get the request handler chain that can handle the dispatch input. :param handler_input: Generic input passed to the dispatcher. :type handler_input: Inpu...
java
protected long getFileDescriptor() throws AsyncException { FieldReturn fRet = AccessController.doPrivileged(new PrivFieldCheck(channel)); if (fRet.e != null) { throw fRet.e; } return fRet.val; }
java
public static MappedByteBuffer map(File file, MapMode mode) throws IOException { checkNotNull(file); checkNotNull(mode); if (!file.exists()) { throw new FileNotFoundException(file.toString()); } return map(file, mode, file.length()); }
java
public static MediaTable create(String tableName, String idColumnName) { return create(tableName, idColumnName, null); }
python
def parse_xml_node(self, node): '''Parse an xml.dom Node object representing a target port into this object. ''' super(TargetPort, self).parse_xml_node(node) self.port_name = node.getAttributeNS(RTS_NS, 'portName') return self
python
def _set_fcoe_fabric_mode(self, v, load=False): """ Setter method for fcoe_fabric_mode, mapped from YANG variable /fcoe/fcoe_fabric_map/fcoe_fabric_mode (fcoe-fabric-mode-type) If this variable is read-only (config: false) in the source YANG file, then _set_fcoe_fabric_mode is considered as a private ...
java
@SuppressWarnings("unchecked") private Segment<K,V> ensureSegment(int k) { final Segment<K,V>[] ss = this.segments; long u = (k << SSHIFT) + SBASE; // raw offset Segment<K,V> seg; if ((seg = (Segment<K,V>)UNSAFE.getObjectVolatile(ss, u)) == null) { Segment<K,V> proto = ss...
java
public Observable<ServiceResponse<Void>> addVideoFrameStreamWithServiceResponseAsync(String teamName, String reviewId, String contentType, byte[] frameImageZip, String frameMetadata, Integer timescale) { if (this.client.baseUrl() == null) { throw new IllegalArgumentException("Parameter this.client.b...
python
def get_next_task(self): """get the next task if there's one that should be processed, and return how long it will be until the next one should be processed.""" if _debug: TaskManager._debug("get_next_task") # get the time now = _time() task = None delta...
java
private static SimpleDateFormat createDateFormat(String pattern, EUniCalendar calendar) { return createDateFormat(pattern, calendar, getDefault()); }
java
public void getFileFromComputeNode(String poolId, String nodeId, String fileName, OutputStream outputStream) throws BatchErrorException, IOException { getFileFromComputeNode(poolId, nodeId, fileName, null, outputStream); }
python
def pre_approval_cancel(self, code): """ cancel a subscribe """ response = self.get(url=self.config.PRE_APPROVAL_CANCEL_URL % code) return PagSeguroPreApprovalCancel(response.content, self.config)
java
protected final void skip_clob_close_punctuation() throws IOException { int c = skip_over_clob_whitespace(); if (c == '}') { c = read_char(); if (c == '}') { return; } unread_char(c); c = '}'; } unread_char(c); ...
java
public static PdfAction rendition(String file, PdfFileSpecification fs, String mimeType, PdfIndirectReference ref) throws IOException { PdfAction js = new PdfAction(); js.put(PdfName.S, PdfName.RENDITION); js.put(PdfName.R, new PdfRendition(file, fs, mimeType)); js.put(new PdfName("OP"),...
java
@Override public ReferenceContext initializeInjectionServices() throws CDIException { Set<Class<?>> injectionClasses = getInjectionClasses(); ReferenceContext referenceContext = archive.getReferenceContext(injectionClasses); return referenceContext; }
python
def hira2hkata(text, ignore=''): """Convert Hiragana to Half-width (Hankaku) Katakana Parameters ---------- text : str Hiragana string. ignore : str Characters to be ignored in converting. Return ------ str Half-width Katakana string. Examples -------- ...
python
async def upload_file(self, data: bytes, mime_type: Optional[str] = None) -> str: """ Upload a file to the content repository. See also: `API reference`_ Args: data: The data to upload. mime_type: The MIME type to send with the upload request. Returns: ...
python
def memoized_parse_block(code): """Memoized version of parse_block.""" success, result = parse_block_memo.get(code, (None, None)) if success is None: try: parsed = COMPILER.parse_block(code) except Exception as err: success, result = False, err else: ...
python
def get(cls, external_id, local_user_id, provider_name, db_session=None): """ Fetch row using primary key - will use existing object in session if already present :param external_id: :param local_user_id: :param provider_name: :param db_session: :return: ...
python
def drawdown_end(self, return_date=False): """The date of the drawdown trough. Date at which the drawdown was most negative. Parameters ---------- return_date : bool, default False If True, return a `datetime.date` object. If False, return a Pandas Times...
java
public void marshall(DescribeTaskExecutionRequest describeTaskExecutionRequest, ProtocolMarshaller protocolMarshaller) { if (describeTaskExecutionRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.mars...
java
public int compareTo(ReadablePartial partial) { // override to perform faster if (this == partial) { return 0; } if (partial instanceof LocalDate) { LocalDate other = (LocalDate) partial; if (iChronology.equals(other.iChronology)) { ret...
python
def thumbnail(self): """ This method returns a thumbnail representation of the file if the data is a supported graphics format. Input: * None Output: * A byte stream representing a thumbnail of a support graphics file Example:: file = clien...
python
async def create_sentinel_pool(sentinels, *, db=None, password=None, encoding=None, minsize=1, maxsize=10, ssl=None, parser=None, timeout=0.2, loop=None): """Create SentinelPool.""" # FIXME: revise default timeout value assert isinstance(sentinel...
python
def info(self): """Formatted string to display the available choices""" if self.descriptions is None: choice_list = ['"{}"'.format(choice) for choice in self.choices] else: choice_list = [ '"{}" ({})'.format(choice, self.descriptions[choice]) ...
python
def _to_mwtab(self): """Save :class:`~mwtab.mwtab.MWTabFile` in `mwtab` formatted string. :return: NMR-STAR string. :rtype: :py:class:`str` """ mwtab_str = io.StringIO() self.print_file(mwtab_str) return mwtab_str.getvalue()
python
def pingback_ping(source, target): """ pingback.ping(sourceURI, targetURI) => 'Pingback message' Notifies the server that a link has been added to sourceURI, pointing to targetURI. See: http://hixie.ch/specs/pingback/pingback-1.0 """ try: if source == target: return UND...
java
public DateTime plusWeeks(int weeks) { if (weeks == 0) { return this; } long instant = getChronology().weeks().add(getMillis(), weeks); return withMillis(instant); }
python
def get_element_pdos(dos, element, sites, lm_orbitals=None, orbitals=None): """Get the projected density of states for an element. Args: dos (:obj:`~pymatgen.electronic_structure.dos.CompleteDos`): The density of states. element (str): Element symbol. E.g. 'Zn'. sites (tuple...
python
def assertion_jwt(client_id, keys, audience, algorithm, lifetime=600): """ Create a signed Json Web Token containing some information. :param client_id: The Client ID :param keys: Signing keys :param audience: Who is the receivers for this assertion :param algorithm: Signing algorithm :para...
python
def offer_url(self): """Offer URL :return: Offer URL (string). """ return "{0}{1}/?tag={2}".format( AMAZON_ASSOCIATES_BASE_URL.format(domain=DOMAINS[self.region]), self.asin, self.aws_associate_tag)
python
def insert(self, i, tag, affix, cmd="hassuf", tagged=None): """ Inserts a new rule that assigns the given tag to words with the given affix, e.g., Morphology.append("RB", "-ly"). """ if affix.startswith("-") and affix.endswith("-"): affix, cmd = affix[+1:-1], "char" ...
java
public TroubleshootingResultInner getTroubleshooting(String resourceGroupName, String networkWatcherName, TroubleshootingParameters parameters) { return getTroubleshootingWithServiceResponseAsync(resourceGroupName, networkWatcherName, parameters).toBlocking().last().body(); }
java
public static <K, V> Lens.Simple<Map<K, V>, Maybe<V>> valueAt(K k) { return adapt(valueAt(HashMap::new, k)); }
java
public final void blendps(XMMRegister dst, Mem src, Immediate imm8) { emitX86(INST_BLENDPS, dst, src, imm8); }
java
public void doDelete(@Param("alarmRuleId") Long alarmRuleId, @Param("pipelineId") Long pipelineId, Navigator nav) throws WebxException { alarmRuleService.remove(alarmRuleId); nav.redirec...
java
public Request<List<Token>> getBlacklist(String audience) { Asserts.assertNotNull(audience, "audience"); String url = baseUrl .newBuilder() .addPathSegments("api/v2/blacklists/tokens") .addQueryParameter("aud", audience) .build() ...
python
def track_child(self, child, logical_block_size, allow_duplicate=False): # type: (DirectoryRecord, int, bool) -> None ''' A method to track an existing child of this directory record. Parameters: child - The child directory record object to add. logical_block_size - Th...
java
public static SelectionSpec[] buildFullTraversal() { List<TraversalSpec> tSpecs = buildFullTraversalV2NoFolder(); // Recurse through the folders TraversalSpec visitFolders = createTraversalSpec("visitFolders", "Folder", "childEntity", new String[]{"visitFolders", "...
python
def append_waiting_queue(self, transfer_coordinator): ''' append item to waiting queue ''' logger.debug("Add to waiting queue count=%d" % self.waiting_coordinator_count()) with self._lockw: self._waiting_transfer_coordinators.append(transfer_coordinator)
python
def unlink(self, key, *keys): """Delete a key asynchronously in another thread.""" return wait_convert(self.execute(b'UNLINK', key, *keys), int)
java
public FilterBuilder includePackage(final String... prefixes) { for (String prefix : prefixes) { add(new Include(prefix(prefix))); } return this; }
java
public SDVariable max(String name, SDVariable x, int... dimensions) { return max(name, x, false, dimensions); }
python
def run(): """CLI main entry point.""" # Use print() instead of logging when running in CLI mode: set_pyftpsync_logger(None) parser = argparse.ArgumentParser( description="Synchronize folders over FTP.", epilog="See also https://github.com/mar10/pyftpsync", parents=[ve...
python
def find_similar(self, doc, min_score=0.0, max_results=100): """ Find `max_results` most similar articles in the index, each having similarity score of at least `min_score`. The resulting list may be shorter than `max_results`, in case there are not enough matching documents. `d...
java
protected static <I, D> void fetchResults(Iterator<DefaultQuery<I, D>> queryIt, List<D> output, int numSuffixes) { for (int j = 0; j < numSuffixes; j++) { DefaultQuery<I, D> qry = queryIt.next(); output.add(qry.getOutput()); } }
python
def set_ref(self, ref_key, ref_id): """ Using a ref key and ref id set the reference to the appropriate resource type. """ if ref_key == 'NETWORK': self.network_id = ref_id elif ref_key == 'NODE': self.node_id = ref_id elif ref_key ...
java
protected void ini() throws CmsException { if (m_container == null) { m_container = new IndexedContainer(); setContainerDataSource(m_container); } else { m_container.removeAllItems(); } for (TableProperty prop : TableProperty.values()) { m...
java
private static boolean containsObject(Object searchFor, Object[] searchIn) { for (int i = 0; i < searchIn.length; i++) { if (searchFor == searchIn[i]) { return true; } } return false; }
java
public static <T extends ImageGray<T>> InterpolatePixelS<T> createPixelS(double min, double max, InterpolationType type, BorderType borderType, Class<T> imageType) { InterpolatePixelS<T> alg; switch( type ) { case NEAREST_NEIGHBOR: alg = nearestNeighborPixelS(imageType); break; case BILINEAR: ...
python
def to_dict(self, save_data=True): """ Store the object into a json serializable dictionary :param boolean save_data: if true, it adds the data self.X and self.Y to the dictionary :return dict: json serializable dictionary containing the needed information to instantiate the object ...
java
private String buildAddSql(final JSONObject jsonObject, final List<Object> paramlist, final StringBuilder sql) throws Exception { String ret = null; if (!jsonObject.has(Keys.OBJECT_ID)) { if (!(KEY_GEN instanceof DBKeyGenerator)) { ret = (String) KEY_GEN.gen(); ...
java
@Override public int prepare(Xid xid) throws XAException { if (logger.logDebug()) { debug("preparing transaction xid = " + xid); } // Check preconditions if (!currentXid.equals(xid)) { throw new CloudSpannerXAException(CloudSpannerXAException.PREPARE_WITH_SAME, Code.UNI...
python
def convert_to_underscore(name): """ "someFunctionWhatever" -> "some_function_whatever" """ s1 = _first_cap_re.sub(r'\1_\2', name) return _all_cap_re.sub(r'\1_\2', s1).lower()
python
def print_number_str(self, value, justify_right=True): """Print a 4 character long string of numeric values to the display. Characters in the string should be any supported character by set_digit, or a decimal point. Decimal point characters will be associated with the previous characte...
java
public Map<String, Object> refundOrder(String orderId, Setup setup) { this.requestMaker = new RequestMaker(setup); RequestProperties props = new RequestPropertiesBuilder() .method("POST") .endpoint(String.format(ENDPOINT_REFUND_ORDER, orderId)) .type(Refun...
java
Class<?> getSetterPropertyType( Clazz<?> clazz, String name ) { ClassInfoCache cache = retrieveCache( clazz ); Class<?> res = cache.getSetterType( name ); if( res != null ) return res; String setterName = "set" + capitalizeFirstLetter( name ); Method setter = clazz.getMethod( setterName ); if( setter !...
python
def _calculate_degree_days(temperature_equivalent, base_temperature, cooling=False): """ Calculates degree days, starting with a series of temperature equivalent values Parameters ---------- temperature_equivalent : Pandas Series base_temperature : float cooling : bool Set True if y...
java
@GwtIncompatible("incompatible method") public static Class<?> getClass(final String className, final boolean initialize) throws ClassNotFoundException { final ClassLoader contextCL = Thread.currentThread().getContextClassLoader(); final ClassLoader loader = contextCL == null ? ClassUtils.class.getC...
java
protected boolean isMethodInstrumentedByThisAdapter() { if (injectedTraceAnnotationVisitor == null) { return false; } List<String> visitedMethodAdapters = injectedTraceAnnotationVisitor.getMethodAdapters(); return visitedMethodAdapters.contains(getClass().getName()); }
python
def get_source(source): """Get the source data for a particular GW catalog """ if source == 'gwtc-1': fname = download_file(gwtc1_url, cache=True) data = json.load(open(fname, 'r')) else: raise ValueError('Unkown catalog source {}'.format(source)) return data['data']
java
@Override public final void cacheMoveValidation(Move<?> move, Validation validation) { validatedMove = move; this.validation = validation; }
java
protected void performScan(Collection<File> created, Collection<File> modified, Collection<File> deleted) { final LinkedHashMap<String, FileInfo> prevScanResult = inMemoryScanResults; final LinkedHashMap<String, FileInfo> newScanResult = new LinkedHashMap<String, FileInfo>(); // Check that dir...
java
@Override public void handle(final ZoomEvent zoomEvent) { final EventType<?> type = zoomEvent.getEventType(); if (ZoomEvent.ZOOM_STARTED == type) { adapter().zoomStarted(zoomEvent); } else if (ZoomEvent.ZOOM == type) { adapter().zoom(zoomEvent); } else if (Z...
python
def has_var_groups(self): '''Returns a set of the variant group ids that this cluster has''' ids = set() for d in self.data: if self._has_known_variant(d) != 'no' and d['var_group'] != '.': ids.add(d['var_group']) return ids
python
def intervals_containing(t, p): """Query the interval tree :param t: root of the interval tree :param p: value :returns: a list of intervals containing p :complexity: O(log n + m), where n is the number of intervals in t, and m the length of the returned list """ INF = float...
python
def init(opts): ''' Open the connection to the Nexsu switch over the NX-API. As the communication is HTTP based, there is no connection to maintain, however, in order to test the connectivity and make sure we are able to bring up this Minion, we are executing a very simple command (``show clock``) ...
python
def parse_references_elements(ref_sect, kbs, linker_callback=None): """Passed a complete reference section, process each line and attempt to ## identify and standardise individual citations within the line. @param ref_sect: (list) of strings - each string in the list is a reference line. ...
java
public static Builder newBuilder(String sourceUri, Schema schema, FormatOptions format) { return newBuilder(ImmutableList.of(sourceUri), schema, format); }
python
def targets_w_bins(cnv_file, access_file, target_anti_fn, work_dir, data): """Calculate target and anti-target files with pre-determined bins. """ target_file = os.path.join(work_dir, "%s-target.bed" % dd.get_sample_name(data)) anti_file = os.path.join(work_dir, "%s-antitarget.bed" % dd.get_sample_name(...
python
def add_latlon_metadata(lat_var, lon_var): """Adds latitude and longitude metadata""" lat_var.long_name = 'latitude' lat_var.standard_name = 'latitude' lat_var.units = 'degrees_north' lat_var.axis = 'Y' lon_var.long_name = 'longitude' lon_var.standard_name = 'longitude' lon_var.units = ...
java
public static SyncPlan computeSyncPlan(Inode inode, Fingerprint ufsFingerprint, boolean containsMountPoint) { Fingerprint inodeFingerprint = Fingerprint.parse(inode.getUfsFingerprint()); boolean isContentSynced = inodeUfsIsContentSynced(inode, inodeFingerprint, ufsFingerprint); boolean isMetadataSync...
java
private boolean checkDataQuality(Optional<Object> schema) throws Exception { if (this.branches > 1) { this.forkTaskState.setProp(ConfigurationKeys.EXTRACTOR_ROWS_EXPECTED, this.taskState.getProp(ConfigurationKeys.EXTRACTOR_ROWS_EXPECTED)); this.forkTaskState.setProp(ConfigurationKeys.EXT...
python
def _get_cur_remotes(path): """Retrieve remote references defined in the CWL. """ cur_remotes = set([]) if isinstance(path, (list, tuple)): for v in path: cur_remotes |= _get_cur_remotes(v) elif isinstance(path, dict): for v in path.values(): cur_remotes |= _g...
java
public static MarkedElement markupBond(IRenderingElement elem, IBond bond) { assert elem != null; MarkedElement tagElem = markupChemObj(elem, bond); tagElem.aggClass("bond"); return tagElem; }
python
def proxy_napalm_wrap(func): ''' This decorator is used to make the execution module functions available outside a proxy minion, or when running inside a proxy minion. If we are running in a proxy, retrieve the connection details from the __proxy__ injected variable. If we are not, then use the...
python
def qualified_name(obj) -> str: """ Return the qualified name (e.g. package.module.Type) for the given object. If ``obj`` is not a class, the returned name will match its type instead. """ if not isclass(obj): obj = type(obj) if obj.__module__ == 'builtins': return obj.__name_...
java
public String convertGSLELINEENDToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); }