language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def remove_reference(type_): """removes reference from the type definition If type is not reference type, it will be returned as is. """ nake_type = remove_alias(type_) if not is_reference(nake_type): return type_ return nake_type.base
java
public static final byte[] getBytes(String text, StandardCharset standardCharset) { try { //Every implementation of the Java platform is required to support the standard charsets //So no point in throwing a checked exception return text.getBytes(standardCharset.charsetName())...
java
public static <T> void forEachWithIndex( Iterable<T> iterable, ObjectIntProcedure<? super T> procedure) { FJIterate.forEachWithIndex(iterable, procedure, FJIterate.FORK_JOIN_POOL); }
java
private static void ensureUserRootExists() throws IOException { if (!m_root.exists()) { if (!m_root.mkdir()) { throw new IOException("Unable to create \"" + m_root + "\""); } } if (!m_root.isDirectory()) { throw new IOException("\"" + m_root + ...
java
@Nonnull public static String escapeXML(CharSequence s) { // double quote -- quot // ampersand -- amp // less than -- lt // greater than -- gt // apostrophe -- apos StringBuilder sb = new StringBuilder(s.length() * 2); for (int i = 0; i < s.length();) { ...
java
void writeStackMapType(Type t) { if (t == null) { if (debugstackmap) System.out.print("empty"); databuf.appendByte(0); } else switch(t.getTag()) { case BYTE: case CHAR: case SHORT: case INT: c...
java
public ApiResponse<ApiSuccessResponse> dndOffWithHttpInfo(MediaDndOffData mediaDndOffData) throws ApiException { com.squareup.okhttp.Call call = dndOffValidateBeforeCall(mediaDndOffData, null, null); Type localVarReturnType = new TypeToken<ApiSuccessResponse>(){}.getType(); return apiClient.exec...
java
public OvhKey serviceName_key_POST(String serviceName, String description, String[] permissions, OvhTag[] tags) throws IOException { String qPath = "/dbaas/timeseries/{serviceName}/key"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "descriptio...
python
def main(): """Run the workflow.""" init_logging() LOG.info("Starting imaging-pipeline") # Read parameters PARFILE = 'parameters.json' if len(sys.argv) > 1: PARFILE = sys.argv[1] LOG.info("JSON parameter file = %s", PARFILE) try: with open(PARFILE, "r") as par_file: ...
python
def get_lat_long(self, callsign, timestamp=timestamp_now): """ Returns Latitude and Longitude for a callsign Args: callsign (str): Amateur Radio callsign timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC) Returns: dict: Containing Latitude and...
python
def extract_components(self): r"""Split the graph into connected components. See :func:`is_connected` for the method used to determine connectedness. Returns ------- graphs : list A list of graph structures. Each having its own node list and weig...
java
private HttpEntity buildBodyWithFile(File file) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM, file.getName()); HttpEntity multipart = builder.build(); return multipart; }
java
private State skipSubPath(State state) throws IOException { for (;;) { switch (state.current) { case -1: case 'm': case 'M': return state; default: break; } state.current =...
python
def extract_workflow(notebook): '''Extract workflow from a notebook file or notebook JSON instance''' if isinstance(notebook, str): nb = nbformat.read(notebook, nbformat.NO_CONVERT) else: nb = notebook cells = nb.cells content = '#!/usr/bin/env sos-runner\n#fileformat=SOS1.0\n\n' ...
java
@Pure public static boolean intersectsOrientedBoxCapsule( double centerx,double centery,double centerz, double axis1x, double axis1y, double axis1z, double axis2x, double axis2y, double axis2z, double axis3x, double axis3y, double axis3z, double extentAxis1, double extentAxis2, double extentAxis3, ...
java
public void write(boolean skipNonOverrides, boolean withXMLDeclaration, PrintWriter writer) { final String indent = " "; // header if (withXMLDeclaration) { writer.println("<?xml version=\"1.0\" encoding=\"UTF-8\...
java
public static Condition withHeader(final String key, final String... expectedHeaders) { return new Condition(input -> { for (Map.Entry<String, List<String>> e : input.getHeaders().entrySet()) { if (e.getKey().equalsIgnoreCase(key)) { return (expectedHeaders == nul...
java
public AABBd setMax(double maxX, double maxY, double maxZ) { this.maxX = maxX; this.maxY = maxY; this.maxZ = maxZ; return this; }
java
public CloseableIterator<String> getSplitIterator(String start, String end, int numSplits) throws IOException { SeekableLineReader slr = factory.get(); long[] offsets = getStartEndOffsets(slr, start, end); return new StepSeekingIterator(slr, offsets[0], offsets[1], numSplits); }
python
def getmembers(self): ''' Return the members of the archive as a list of RPMInfo objects. The list has the same order as the members in the archive. ''' if self._members is None: self._members = _members = [] g = self.data_file magic = g.read(2...
java
public Calendar floor(long t) { Calendar cal = new GregorianCalendar(Locale.US); cal.setTimeInMillis(t); return floor(cal); }
python
def svd_to_stream(uvectors, stachans, k, sampling_rate): """ Convert the singular vectors output by SVD to streams. One stream will be generated for each singular vector level, for all channels. Useful for plotting, and aiding seismologists thinking of waveforms! :type svectors: list :par...
python
def item(self, infohash, prefetch=None, cache=False): """ Fetch a single item by its info hash. """ return next(self.items(infohash, prefetch, cache))
python
def render_request(self): """ Create a :class:`Data` object containing all fields known to the :class:`Form`. If the :class:`Form` has a :attr:`LAYOUT` attribute, it is used during generation. """ data = forms_xso.Data(type_=forms_xso.DataType.FORM) try: ...
java
public static <T> JsonObjectBase buildListSuccess(List<?> value, int totalCount, T footResult) { JsonObjectList json = new JsonObjectList(); json.setPage(totalCount); json.addData(value); json.addFootData(footResult); LOG.info(json.toString()); return json; }
python
def vector_plot(X, Y, U, V, t, skip=5, *, t_axis=0, units='', fps=10, pcolor_kw={}, quiver_kw={}): """produces an animation of vector fields This takes 2D vector field, and plots the magnitude as a pcolomesh, and the normalized direction as a quiver plot. It then animates it. This is a...
java
public ClassNode visitAnnotatedClasses($.Visitor<ClassNode> visitor) { for (ClassNode annotated : this.annotated) { visitor.apply(annotated); } return this; }
java
public void updateTenant(Tenant updatedTenant) { assert m_tenant.getName().equals(updatedTenant.getName()); m_tenant = updatedTenant; }
python
def do(self, params): """发起对 api 的请求并过滤返回结果 :param params: 交易所需的动态参数""" request_params = self.create_basic_params() request_params.update(params) response_data = self.request(request_params) try: format_json_data = self.format_response_data(response_data) ...
python
def update_exc(base_exceptions, *addition_dicts): """Update and validate tokenizer exceptions. Will overwrite exceptions. base_exceptions (dict): Base exceptions. *addition_dicts (dict): Exceptions to add to the base dict, in order. RETURNS (dict): Combined tokenizer exceptions. """ exc = dict(...
python
def decode(stream, strict=True): """ Decodes a SOL stream. L{strict} mode ensures that the sol stream is as spec compatible as possible. @return: A C{tuple} containing the C{root_name} and a C{dict} of name, value pairs. """ if not isinstance(stream, util.BufferedByteStream): st...
java
@Override public String getRemoteHost() { ServletRESTRequestImpl ret = castRequest(); if (ret != null) return ret.getRemoteHost(); return null; }
java
protected static SiftsChainToUniprotMapping build() throws IOException { SiftsChainToUniprotMapping sifts = new SiftsChainToUniprotMapping(); BufferedReader br = new BufferedReader(new FileReader(DEFAULT_FILE)); String line = ""; while ((line = br.readLine()) != null) { if (line.isEmpty() || line.startsWith(...
java
public void modelNormalInstruction(Instruction ins, int numWordsConsumed, int numWordsProduced) { modelInstruction(ins, numWordsConsumed, numWordsProduced, getDefaultValue()); }
java
private boolean isKnownException(@SlashedClassName String clsName) { for (String exceptionCls : knownExceptions) { if (clsName.startsWith(exceptionCls)) { return true; } } return false; }
python
def saved_searches(self): """ :reference: https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list """ return bind_api( api=self, path='/saved_searches/list.json', payload_type='saved_search', payload_list=...
python
def get_workflows_for(brain_or_object): """Get the assigned workflows for the given brain or context. Note: This function supports also the portal_type as parameter. :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain ...
java
public static List<CommerceTaxFixedRate> findByCPTaxCategoryId( long CPTaxCategoryId, int start, int end) { return getPersistence() .findByCPTaxCategoryId(CPTaxCategoryId, start, end); }
java
public static Class<?> getUserClass(Class<?> clazz) { if (clazz != null && clazz.getName().contains(CGLIB_CLASS_SEPARATOR)) { Class<?> superClass = clazz.getSuperclass(); if (superClass != null && !Object.class.equals(superClass)) { return superClass; } } return clazz; }
python
def connect( host='localhost', user=None, password=None, port=3306, database=None, url=None, driver='pymysql', ): """Create an Ibis client located at `user`:`password`@`host`:`port` connected to a MySQL database named `database`. Parameters ---------- host : string, def...
python
def trim(args): """ %prog trim fastqfile Wraps `fastx_trimmer` to trim from begin or end of reads. """ p = OptionParser(trim.__doc__) p.add_option("-f", dest="first", default=0, type="int", help="First base to keep. Default is 1.") p.add_option("-l", dest="last", default=0, type...
java
public static service_binding get(nitro_service service, String name) throws Exception{ service_binding obj = new service_binding(); obj.set_name(name); service_binding response = (service_binding) obj.get_resource(service); return response; }
python
async def process_response( self, response: Response, request_context: Optional[RequestContext]=None, ) -> Response: """Postprocess the request acting on the response. Arguments: response: The response after the request is finalized. request_context: ...
python
def userinfo_claims(self, access_token, scope_request, claims_request): """ Return the claims for the requested parameters. """ id_token = oidc.userinfo(access_token, scope_request, claims_request) return id_token.claims
python
def build(self): """ Builds this object into the desired output information. """ signed = bool(self.options() & Builder.Options.Signed) # remove previous build information buildpath = self.buildPath() if not buildpath: raise errors.InvalidBuildPath(bu...
python
def avl_join_dir_recursive(t1, t2, node, direction): """ Recursive version of join_left and join_right TODO: make this iterative using a stack """ other_side = 1 - direction if _DEBUG_JOIN_DIR: print('--JOIN DIR (dir=%r) --' % (direction,)) ascii_tree(t1, 't1') ascii_tree...
java
@Override public synchronized void init(DataGenerator dataGenerator) throws Exception { if (esConfig.getRestClientPort() == 443 && !esConfig.isHttps()) { throw new IllegalArgumentException( "You must set the configuration property 'https' to true if you use the https default ...
java
public void marshall(ECSTarget eCSTarget, ProtocolMarshaller protocolMarshaller) { if (eCSTarget == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(eCSTarget.getDeploymentId(), DEPLOYMENTID_BINDING); ...
java
public static void writeStaticField(final Class<?> cls, final String fieldName, final Object value, final boolean forceAccess) throws IllegalAccessException { final Field field = getField(cls, fieldName, forceAccess); Validate.isTrue(field != null, "Cannot locate field %s on %s", fieldName, ...
python
def __marshal_matches(matched): """Convert matches to JSON format. :param matched: a list of matched identities :returns json_matches: a list of matches in JSON format """ json_matches = [] for m in matched: identities = [i.uuid for i in m] if l...
python
def encode_leaf_node(value): """ Serializes a leaf node """ validate_is_bytes(value) if value is None or value == b'': raise ValidationError("Value of leaf node can not be empty") return LEAF_TYPE_PREFIX + value
java
public void addAttribute(String attributeName, String attributeValue) throws XmlModelException { String name = attributeName.trim(); String value = attributeValue.trim(); if(attributesMap.containsKey(name)) { throw new XmlModelException("Duplicate attribute: " + name); } ...
python
def package_maven(): """ Run maven package lifecycle """ if not os.getenv('JAVA_HOME'): # make sure Maven uses the same JDK which we have used to compile # and link the C-code os.environ['JAVA_HOME'] = jdk_home_dir mvn_goal = 'package' log.info("Executing Maven goal '" + mvn_goa...
java
INode unprotectedDelete(String src, INode inodes[], List<BlockInfo> toBeDeletedBlocks, int blocksLimit, long modificationTime) { src = normalizePath(src); writeLock(); try { INode targetNode = inodes[inodes.length-1]; if (targetNode == null) { // non-existent src ...
java
@Override public BufferedImage read(final int pIndex, final ImageReadParam pParam) throws IOException { init(); checkBounds(pIndex); // Quick look-up BufferedImage image = null; if (pIndex < thumbnails.length) { image = thumbnails[pIndex]; } if (...
java
void savePreviousActionInfo( ActionForm form, HttpServletRequest request, ActionMapping mapping, ServletContext servletContext ) { // // If previous-action is disabled (unused in this pageflow), just return. // if ( isPreviousActionInfoDisabled() ) re...
python
def arguments_to_lists(function): """ Decorator for a function that converts all arguments to lists. :param function: target function :return: target function with only lists as parameters """ def l_function(*args, **kwargs): l_args = [_to_list(arg) for arg in args] l_kw...
python
def _parse_aot(self, first, name_first): # type: (Table, str) -> AoT """ Parses all siblings of the provided table first and bundles them into an AoT. """ payload = [first] self._aot_stack.append(name_first) while not self.end(): is_aot_next, name_nex...
java
private List<String> parseMethodParams(String methodParameters, Node methodSignature) { List<String> parsedParameters = new ArrayList<>(); char nextDelimeter = ','; String currentTerm = ""; for (int i = 0; i < methodParameters.length(); i++) { if (methodParameters.charAt(i) == nextDelimeter) { ...
python
def new_from_sha(cls, repo, sha1): """ :return: new object instance of a type appropriate to represent the given binary sha1 :param sha1: 20 byte binary sha1""" if sha1 == cls.NULL_BIN_SHA: # the NULL binsha is always the root commit return get_object_...
python
def createSimulate (netParams=None, simConfig=None, output=False): ''' Sequence of commands create, simulate and analyse network ''' from .. import sim (pops, cells, conns, stims, rxd, simData) = sim.create(netParams, simConfig, output=True) sim.simulate() if output: return (pops, cells, conns, st...
java
public static byte[] encrypt(String key, String iv, byte[] data, String cipherTransformation) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException { return encrypt(key.getBytes(Sta...
python
def engine_from_environment() -> Engine: """Returns an Engine instance configured using environment variables. If the environment variables are set, but incorrect, an authentication failure will occur when attempting to run jobs on the engine. Required Environment Variables: QUANTUM_ENGINE_PRO...
java
@Override public Collection<Response> getResponses(String earliest) throws NotAuthorizedException { SearchCriteria criteria = new SearchCriteria(). setDetectionSystemIds(StringUtils.toCollection(detectionSystemId != null ? detectionSystemId : "")). setEarliest(earliest); return appSensorServer.getRespon...
java
public JsonObject optJsonObject(int index) { JsonElement el; try { el = get(index); } catch (JsonException e) { return null; } if (!el.isJsonObject()) { return null; } return el.asJsonObject(); }
python
def update_frame(self, key, ranges=None, plot=None): """ Updates an existing plot with data corresponding to the key. """ element = self._get_frame(key) self._get_title_div(key, '12pt') # Cache frame object id to skip updating data if unchanged previous_i...
java
private void getWSDL(String api, String requestURL, PrintWriter out) throws IOException, ServletException { String wsdlPath = (String) _WSDL_PATHS.get(api); if (wsdlPath != null) { File schemaFile = new File(_serverDir, _XSD_PATH); File sourceWSDL = new File(_server...
java
public static ImmutableVector3 copy(Vector3 source) { if (source instanceof ImmutableVector3) return (ImmutableVector3)source; return createVector(source.getX(), source.getY(), source.getZ()); }
python
def _to_pb(self): """ Create cluster proto buff message for API calls """ client = self._instance._client location = client.instance_admin_client.location_path( client.project, self.location_id ) cluster_pb = instance_pb2.Cluster( location=location, ...
python
def insert(self, var, value, index=None): """Insert at the index. If the index is not provided appends to the end of the list. """ current = self.__get(var) if not isinstance(current, list): raise KeyError("%s: is not a list" % var) if index is None: ...
java
@SuppressWarnings("unchecked") public static <Item> Item[] flatten(final Item... items) { return (Item[]) flattenAsStream(items).toArray(Object[]::new); }
python
def enable_gtk(self, app=None): """Enable event loop integration with PyGTK. Parameters ---------- app : ignored Ignored, it's only a placeholder to keep the call signature of all gui activation methods consistent, which simplifies the logic of supportin...
java
private DataSet<Edge<K, EV>> getPairwiseEdgeIntersection(DataSet<Edge<K, EV>> edges) { return this.getEdges() .coGroup(edges) .where(0, 1, 2) .equalTo(0, 1, 2) .with(new MatchingEdgeReducer<>()) .name("Intersect edges"); }
java
public static boolean isInAlphabet(final char pCharToCheck) { for (int i = 0; i < ALPHABET.length; i++) { if (pCharToCheck == ALPHABET[i]) { return true; } } return false; }
java
synchronized Future<UpdateCenterJob> addJob(UpdateCenterJob job) { addConnectionCheckJob(job.site); return job.submit(); }
python
def get_agg(self): """ Returns the aggregated value for the metric :return: the value of the metric """ """ Returns an aggregated value """ query = self.get_query(False) res = self.get_metrics_data(query) # We need to extract the data from the JSON res ...
java
@OptionDesc(longName = "locale", shortName = "l", description = "citation LOCALE (default: en-US)", argumentName = "LOCALE", argumentType = ArgumentType.STRING, priority = 30) public void setLocale(String locale) { this.locale = locale; }
python
def getAxisNames(self): """ Collect a set of axis names from all deltas. """ s = {} for l, x in self.items(): s.update(dict.fromkeys([k for k, v in l], None)) return set(s.keys())
python
def zip_built(outdir): """Packages the build folder into a zip""" print("Zipping the built files!") config_file_dir = os.path.join(cwd, "config.py") if not os.path.exists(config_file_dir): sys.exit( "There dosen't seem to be a configuration file. Have you run the init command?") ...
python
def merge_bams(self, input_bams, merged_bam, in_sorted="TRUE", tmp_dir=None): """ Combine multiple files into one. The tmp_dir parameter is important because on poorly configured systems, the default can sometimes fill up. :param Iterable[str] input_bams: Paths to files to comb...
python
def attrsignal(descriptor, signal_name, *, defer=False): """ Connect the decorated method or coroutine method to the addressed signal on a descriptor. :param descriptor: The descriptor to connect to. :type descriptor: :class:`Descriptor` subclass. :param signal_name: Attribute name of the signa...
java
public static String executeGroovy(String script, @Nonnull VirtualChannel channel) throws IOException, InterruptedException { return channel.call(new Script(script)); }
python
def filter_cells( data: AnnData, min_counts: Optional[int] = None, min_genes: Optional[int] = None, max_counts: Optional[int] = None, max_genes: Optional[int] = None, inplace: bool = True, copy: bool = False, ) -> Optional[Tuple[np.ndarray, np.ndarray]]: """Filter cell outliers based o...
java
@Override public String getContentType() { ServletRESTRequestImpl ret = castRequest(); if (ret != null) return ret.getContentType(); return null; }
java
@Override public CompletableFuture<Map<String, Change<?>>> diff(Revision from, Revision to, String pathPattern) { final ServiceRequestContext ctx = context(); return CompletableFuture.supplyAsync(() -> { requireNonNull(from, "from"); requireNonNull(to, "to"); requ...
python
def graphStats(G, stats = ('nodes', 'edges', 'isolates', 'loops', 'density', 'transitivity'), makeString = True, sentenceString = False): """Returns a string or list containing statistics about the graph _G_. **graphStats()** gives 6 different statistics: number of nodes, number of edges, number of isolates, n...
java
private void doListNode(final Message<JsonObject> message) { context.execute(new Action<Collection<String>>() { @Override public Collection<String> perform() { List<String> nodes = new ArrayList<>(); for (String group : groups.keySet()) { nodes.addAll(groups.get(group)); ...
python
def load_ipa_data(): """ Load the IPA data from the built-in IPA database, creating the following globals: 1. ``IPA_CHARS``: list of all IPAChar objects 2. ``UNICODE_TO_IPA``: dict mapping a Unicode string (often, a single char) to an IPAChar 3. ``UNICODE_TO_IPA_MAX_KEY_LENGTH``: length of a longes...
python
def _handle_expander_message(self, data): """ Handle expander messages. :param data: expander message to parse :type data: string :returns: :py:class:`~alarmdecoder.messages.ExpanderMessage` """ msg = ExpanderMessage(data) self._update_internal_states(m...
python
def form_valid(self, form): """ The request from ulogin service is correct """ response = self.ulogin_response(form.cleaned_data['token'], self.request.get_host()) if 'error' in response: return render(self.request, self.error_...
java
public Pair<Integer> nextPair(int prevN1, int prevN2) { if (prevN1 == NULL_NODE) prevN1 = 0; if (prevN2 == NULL_NODE) prevN2 = 0; else prevN2++; if (t1bothLen>coreLen && t2bothLen > coreLen) { while (prevN1 < n1 && (core1[prevN1] != NULL_NODE ...
python
def get_fmt_widget(self, parent, project): """Create a combobox with the attributes""" from psy_simple.widgets.texts import LabelWidget return LabelWidget(parent, self, project)
python
def _build_circle(self): """ Creates hash ring. """ total_weight = 0 for node in self._nodes: total_weight += self._weights.get(node, 1) for node in self._nodes: weight = self._weights.get(node, 1) ks = math.floor((40 * len(self._...
python
def diff(self, path_a, path_b): """ Performs a deep comparison of path_a/ and path_b/ For each child, it yields (rv, child) where rv: -1 if doesn't exist in path_b (destination) 0 if they are different 1 if it doesn't exist in path_a (source) """ ...
java
@Override public CPInstance fetchByC_NotST_First(long CPDefinitionId, int status, OrderByComparator<CPInstance> orderByComparator) { List<CPInstance> list = findByC_NotST(CPDefinitionId, status, 0, 1, orderByComparator); if (!list.isEmpty()) { return list.get(0); } return null; }
java
@Deprecated public Captions withCaptionSources(java.util.Collection<CaptionSource> captionSources) { setCaptionSources(captionSources); return this; }
java
public void updateGroupList() { Map<?, ?> objects = (Map<?, ?>)getSettings().getListObject(); if (objects != null) { objects.remove(CmsGroupsList.class.getName()); objects.remove(A_CmsUsersList.class.getName()); } }
java
public void copyResourceToClassesOutput(String path, String filename) { String fullpath = path + ProcessorConstants.SEPARATORCHAR + filename; messager.printMessage(Diagnostic.Kind.MANDATORY_WARNING, " javascript copy js : " + fullpath + " to : class dir"); try (Writer writer = getFileObjectWriterInClassOutput("",...
java
protected void removeBifurcatedConsumer(BifurcatedConsumerSessionImpl consumer) throws SIResourceException, SISessionDroppedException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "removeBifurcatedConsumer", consumer); synchronized (_bifurcatedConsum...
python
def setup_logging(format="%(asctime)s - %(levelname)s - %(message)s", level='INFO'): """Setup the logging framework with a basic configuration""" try: import coloredlogs coloredlogs.install(fmt=format, level=level) except ImportError: logging.basicConfig(format=format, level=level)