language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def run(self, templ, *args): """ A simple utility to run SQL queries. :param templ: a query or query template :param args: the arguments (or the empty tuple) :returns: the DB API 2 cursor used to run the query """ curs = self._conn.cursor() query = curs.m...
java
public Map<String, Object> getInboundConnectionInfo() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) Tr.entry(tc, "getInboundConnectionInfo"); Map<String, Object> inboundConnectionInfo = ThreadManager.getInstance().getInboundConnectionInfo(); if (TraceComponent.is...
java
public void logDebug(String message, Exception exception) { if (!(logDebug || globalLog.logDebug)) return; if (debugLog != null) log(debugLog, "DEBUG", owner, message, exception); else log(globalLog.debugLog, "DEBUG", owner, message, exception); ...
python
def read_content(path: str, limit: Optional[int] = None) -> Iterator[List[str]]: """ Returns a list of tokens for each line in path up to a limit. :param path: Path to files containing sentences. :param limit: How many lines to read from path. :return: Iterator over lists of words. """ with...
java
static public boolean isMouseWithinComponent(Component component) { Point mousePos = MouseInfo.getPointerInfo().getLocation(); Rectangle bounds = component.getBounds(); bounds.setLocation(component.getLocationOnScreen()); return bounds.contains(mousePos); }
java
public static void loadCompressedTexture(final GVRContext gvrContext, final ResourceCache<GVRImage> textureCache, final CompressedTextureCallback callback, final GVRAndroidResource resource, final int quality) throws IllegalArgumentException { validateCallbackPara...
python
def render_template_string(self, plain, rich = None, **context): '''Render the body of the message from a string. If ``rich`` isn’t provided then the message will not have a rich body.''' self.plain = render_template_string(plain, **context) if rich is not None: self.rich = ...
python
def taxonomy_from_annotated_tree(self, dendropy_tree): '''Given an annotated dendropy tree, return the taxonomy of each tip Parameters --------- tree: dendropy.Tree Decorated tree to extract taxonomy from Returns ------- dictionary of t...
java
public static Map<String, String> getSiblings(final String prefix) { Map<String, String> map = new HashMap<String, String>(); for (Enumeration<Object> enumeration = properties.keys(); enumeration.hasMoreElements();) { String key = (String) enumeration.nextElement(); if (key.startsWith(prefix) && (prefix.endsW...
python
def get_topic(self): """ Returns the considered topic if applicable. """ pk = self.kwargs.get(self.topic_pk_url_kwarg, None) if not pk: return if not hasattr(self, '_topic'): self._topic = get_object_or_404(Topic, pk=pk) return self._topic
java
public void marshalling(Xdr xdr) { super.marshalling(xdr); xdr.putLong(_cookie); xdr.putLong(_cookieverf); xdr.putUnsignedInt(_count); }
java
public void marshall(CustomDomainConfigType customDomainConfigType, ProtocolMarshaller protocolMarshaller) { if (customDomainConfigType == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(customDomainC...
python
def tagdict(self): """return a dict converted from this string interpreted as a tag-string .. code-block:: py >>> from pprint import pprint >>> dict_ = IrcString('aaa=bbb;ccc;example.com/ddd=eee').tagdict >>> pprint({str(k): str(v) for k, v in dict_.items()}) ...
java
public String interval(Date target) { double unit = 1000.0D; double dayUnit = DAY / unit; double hourUnit = HOUR / unit; double minUnit = MINUTE / unit; double interval = sinceMillis(target) / unit; IntervalDesc desc = theIntervalDesc.get(); if (interval >= 0.0D) { if (interval / (12 * 30 * dayUnit)...
python
def kana_romaji_lt(romaji, *kana): ''' Generates a lookup table with the kana characters on the left side and their rōmaji equivalents as the values. For the consonant-vowel (cv) characters, we'll generate: {u'か': ('ka', 'k', 'k', 'ā'), u'が': ('ga', 'g', 'g', 'ā'), [...] Mu...
python
def schema_complete(): """Schema for data in CollectorStage.""" return Schema({ 'stage': And(str, len), 'status': And(str, lambda s: s in ['started', 'succeeded', 'failed']), Optional('events', default=[]): And(len, [CollectorStage.schema_event_items()]) })
python
def wrap_udf(hdfs_file, inputs, output, so_symbol, name=None): """ Creates a callable scalar function object. Must be created in Impala to be used Parameters ---------- hdfs_file: .so file that contains relevant UDF inputs: list of strings or sig.TypeSignature Input types to UDF o...
java
public static <T> void register(final Class<T> service) { for (T each : ServiceLoader.load(service)) { registerServiceClass(service, each); } }
python
def delete(self, path, data=None, headers=None, params=None): """ Deletes resources at given paths. :rtype: dict :return: Empty dictionary to have consistent interface. Some of Atlassian REST resources don't return any content. """ self.request('DELETE', path=path...
python
def build(self, builder): """ Build XML by appending to builder """ params = dict(LocationOID=self.oid) # mixins self.mixin() self.mixin_params(params) builder.start("SiteRef", params) builder.end("SiteRef")
python
def fetch_album_name(self): """ Get the name of the album from lastfm. """ response = get_lastfm('track.getInfo', artist=self.artist, track=self.title) if response: try: self.album = response['track']['album']['title'] ...
java
public java.util.Map<java.lang.String, alluxio.grpc.InconsistentProperties> getErrorsMap() { return internalGetErrors().getMap(); }
python
def get_library_instance(self, library_path, library_name): """Generate a Library instance from within libraries dictionary tree.""" if self.is_library_in_libraries(library_path, library_name): from rafcon.core.states.library_state import LibraryState return LibraryState(library_...
python
def render(self, ctx=None): ''' :param ctx: rendering context in which the method was called :rtype: `Bits` :return: rendered value of the container ''' super(Trunc, self).render(ctx) self._current_value = self._current_rendered self._current_rendered = se...
python
def create_new_file(help_string=NO_HELP, default=NO_DEFAULT, suffixes=None): # type: (str, Union[str, NO_DEFAULT_TYPE], Union[List[str], None]) -> str """ Create a new file parameter :param help_string: :param default: :param suffixes: :return: """ ...
python
def pop(self, key=-1): """Removes and returns an item at a given index. Similar to list.pop().""" value = self._values[key] self.__delitem__(key) return value
python
def ReadClientLastPings(self, min_last_ping=None, max_last_ping=None, fleetspeak_enabled=None, cursor=None): """Reads client ids for all clients in the database.""" query = "SELECT client_id, UNIX_TIMESTAMP(l...
python
def _build_command(self, cmd_1, cmd_2, select=False, select_command=None): """ Constructs the complete command. :param cmd_1: Light command 1. :param cmd_2: Light command 2. :return: The complete command. """ return CommandV6(cmd_1, cmd_2, ...
java
public DatabaseConnectionRequest<T, U> addParameters(Map<String, Object> parameters) { request.addParameters(parameters); return this; }
python
def evpn_next_hop_unchanged(self, **kwargs): """Configure next hop unchanged for an EVPN neighbor. You probably don't want this method. You probably want to configure an EVPN neighbor using `BGP.neighbor`. That will configure next-hop unchanged automatically. Args: ...
java
public static void write(Node node, OutputStream outputStream) { OutputStreamWriter writer = new OutputStreamWriter(outputStream); write(node, writer, 4, false); }
java
public static Object decodeToObject(String encodedObject, int options, final ClassLoader loader) throws IOException, ClassNotFoundException { // Decode and gunzip if necessary byte[] objBytes = decode(encodedObject, options); ByteArrayInputStream bais = null; ObjectInputStream ois = null; Object ob...
java
public static StoreWriter createWriter(File file, Configuration config) { return StoreImpl.createWriter(file, config); }
python
def create_prefix_dir(nb_file, fmt): """Create directory if fmt has a prefix""" if 'prefix' in fmt: nb_dir = os.path.dirname(nb_file) + os.path.sep if not os.path.isdir(nb_dir): logging.log(logging.WARNING, "[jupytext] creating missing directory %s", nb_dir) os.makedirs(n...
python
def sum_filter(input, size=None, footprint=None, output=None, mode="reflect", cval=0.0, origin=0): r""" Calculates a multi-dimensional sum filter. Parameters ---------- input : array-like input array to filter size : scalar or tuple, optional See footprint, below footprint :...
java
protected Field createFulltextField(String value, boolean store, boolean withOffsets) { return new Field(FieldNames.FULLTEXT, value, store ? Field.Store.YES : Field.Store.NO, Field.Index.ANALYZED, withOffsets ? Field.TermVector.WITH_OFFSETS : Field.TermVector.NO); }
java
public String findTypeWithMatchingNamespace(String prefix) { prefix = prefix + "."; // This must be sorted so that errors are deterministic, or we'll break integration tests. for (String name : getAllSortedTypeNames()) { if (name.startsWith(prefix)) { return name; } } return null...
java
public <T extends Enum<T>> EnumSet<T> getParametersAsEnums(String name, Class<T> type, EnumSet<T> defaultValue) { String[] enumNames = getParameters(name); if (enumNames == null) { return defaultValue; } else { Collection<T> enums = new ArrayList<>(); for (String enumName : enumNames) { T enum...
java
public static Payout retrieve(String payout) throws StripeException { return retrieve(payout, (Map<String, Object>) null, (RequestOptions) null); }
python
def _warn_if_string(iterable): """Helper for the response objects to check if the iterable returned to the WSGI server is not a string. """ if isinstance(iterable, string_types): from warnings import warn warn(Warning('response iterable was set to a string. This appears ' ...
python
def type_assert_iter( iterable, cls, cast_from=None, cast_to=None, dynamic=None, objcls=None, choices=None, ctor=None, allow_none=False, ): """ Checks that every object in @iterable is an instance of @cls Will also unmarshal JSON objects to Python objects if items in ...
java
public void loadField(String fieldName, TypeDesc type) { getfield(0, Opcode.GETFIELD, constantField(fieldName, type), type); }
java
@Trivial public static ZipEntryData[] collectZipEntries(ZipFile zipFile) { final List<ZipEntryData> entriesList = new ArrayList<ZipEntryData>(); final Enumeration<? extends ZipEntry> zipEntries = zipFile.entries(); while ( zipEntries.hasMoreElements() ) { entriesList.add( create...
java
public DrawerBuilder withActivity(@NonNull Activity activity) { this.mRootView = (ViewGroup) activity.findViewById(android.R.id.content); this.mActivity = activity; this.mLayoutManager = new LinearLayoutManager(mActivity); return this; }
python
def gpio_properties(self): """Returns the properties of the user-controllable GPIOs. Provided the device supports user-controllable GPIOs, they will be returned by this method. Args: self (JLink): the ``JLink`` instance Returns: A list of ``JLinkGPIODescrip...
python
def makeIdentifiers(blocks, target="sentenceContainsTarget(+SID,+WID).", treeDepth="3", nodeSize="3", numOfClauses="8"): """ Make unique identifiers for components of the block and write to files. :param blocks: Blocks of sentences (likely the output of ``textprocessi...
python
def overlaps(self, other): """ Return true if a rectangle overlaps this rectangle. """ return ( self.right > other.left and self.left < other.right and self.top < other.bottom and self.bottom > other.top )
python
def partitioned_probability(self, direction, partition): """Compute the probability of the mechanism over the purview in the partition. """ repertoire = self.partitioned_repertoire(direction, partition) return self.state_probability(direction, repertoire, partition.purview)
java
public final void mT__63() throws RecognitionException { try { int _type = T__63; int _channel = DEFAULT_TOKEN_CHANNEL; // BELScript.g:50:7: ( 'sec' ) // BELScript.g:50:9: 'sec' { match("sec"); } state.type = _ty...
java
public static Iterable<String> iterate(final String node) { return new Iterable<String>() { @Override public Iterator<String> iterator() { return new Scanner(node).useDelimiter("/"); } }; }
python
def _path_with_dir_fd(self, path, fct, dir_fd): """Return the path considering dir_fd. Raise on nmvalid parameters.""" if dir_fd is not None: if sys.version_info < (3, 3): raise TypeError("%s() got an unexpected keyword " "argument 'dir_fd'" % ...
java
public LogTarget addDelegate(Log log) { LogProxyTarget logProxyTarget = new LogProxyTarget(log); this.addTarget(logProxyTarget); return logProxyTarget; }
java
public List<JavaClass> getAllClasses() { ClassDumpSegment classDumpBounds; if (heapDumpSegment == null) { return Collections.emptyList(); } classDumpBounds = getClassDumpSegment(); if (classDumpBounds == null) { return Collections.emptyList(); }...
python
def list_archive(archive, verbosity=1, program=None, interactive=True): """List given archive.""" # Set default verbosity to 1 since the listing output should be visible. util.check_existing_filename(archive) if verbosity >= 0: util.log_info("Listing %s ..." % archive) return _handle_archive...
python
def _prune_previous_versions(self, symbol, keep_mins=120, keep_version=None, new_version_shas=None): """ Prune versions, not pointed at by snapshots which are at least keep_mins old. Prune will never remove all versions. """ new_version_shas = new_version_shas if new_version_shas...
java
@VisibleForTesting static String canonicalizeHost(String host) { if (host.startsWith("[") && host.endsWith("]")) { return host.substring(1, host.length() - 1); } return host; }
python
def get_all(rc_file='~/.odoorpcrc'): """Return all session configurations from the `rc_file` file. >>> import odoorpc >>> from pprint import pprint as pp >>> pp(odoorpc.session.get_all()) # doctest: +SKIP {'foo': {'database': 'db_name', 'host': 'localhost', 'passwd': '...
python
def set_time(time): ''' Sets the current time. Must be in 24 hour format. :param str time: The time to set in 24 hour format. The value must be double quoted. ie: '"17:46"' :return: True if successful, False if not :rtype: bool :raises: SaltInvocationError on Invalid Time format ...
python
def object_permission_set(self): '''All users have view permissions. Admin users, and users with org:admin can create, update, and delete any user. Any user can update or delete themselves. Only admins can create or modify other admin users.''' return Or( AllowOnlySaf...
java
public String authority() { String authority = this.authority; if (authority != null) { return authority; } if (isGroup()) { authority = "group:" + groupName; } else if (port != 0) { if (hostType == HostType.IPv6_ONLY) { author...
java
@Processor public Object logWarning( @Optional @FriendlyName("Log Message") String message, @Optional String integrationScenario, @Optional String messageType, @Optional String contractId, @Optional String correlationId, @Optional @FriendlyName("Extra Info") Map<String, String> extra...
java
@Deprecated @Override public void addModel(String name, Object value) { getInvocation().addModel(name, value); }
java
public Map<String, Float> findSynonyms(String target, int cnt) { float[] vec = transform(target); if ((vec == null) || (cnt == 0)) return Collections.emptyMap(); int[] synonyms = new int[cnt]; float[] scores = new float[cnt]; int min = 0; for (int i = 0; i < cnt; i++) { synonyms[...
java
public static void writeInt32LE(final int value, final byte[] buffer, int offset) { buffer[offset++] = (byte) ((value >>> 0) & 0xFF); buffer[offset++] = (byte) ((value >>> 8) & 0xFF); buffer[offset++] = (byte) ((value >>> 16) & 0xFF); buffer[offset] = (byte) ((value >>> 24) & 0x...
python
def parse(cls, fptr, offset, length): """Parse UUID box. Parameters ---------- fptr : file Open file object. offset : int Start position of box in bytes. length : int Length of the box in bytes. Returns ------- ...
java
public CompletableFuture<Collection<JobStatusMessage>> listJobs() { return runDispatcherCommand(dispatcherGateway -> dispatcherGateway .requestMultipleJobDetails(rpcTimeout) .thenApply(jobs -> jobs.getJobs().stream() .map(details -> new JobStatusMessage(details.getJobId(), details.getJobName(), ...
python
def fw_update(self, data, fw_name=None): """Top level FW update function. """ LOG.debug("FW Update %s", data) self._fw_update(fw_name, data)
python
async def delete(self): """ Delete task (in any state) permanently. Returns `True` is task is deleted. """ the_tuple = await self.queue.delete(self.tube, self.task_id) self.update_from_tuple(the_tuple) return bool(self.state == DONE)
java
public static long toLong(@Nullable final String longStr) { if (!isValidLong(longStr)) { throw new IllegalArgumentException(longStr + ExceptionValues.EXCEPTION_DELIMITER + ExceptionValues.INVALID_LONG_VALUE); } final String stripedLong = StringUtils.strip(longStr); return Num...
python
def get_input(prompt, default=None, choices=None, option_value=None): """ If option_value is not None, then return it. Otherwise get the result from input. """ if option_value is not None: return option_value choices = choices or [] while 1: r = input(prompt+' ').strip(...
python
def replace(self, html): """Perform replacements on given HTML fragment.""" self.html = html text = html.text() positions = [] def perform_replacement(match): offset = sum(positions) start, stop = match.start() + offset, match.end() + offset ...
python
async def vcx_messages_update_status(msg_json: str): """ Update the status of messages from the specified connection :param msg_json: :return: """ logger = logging.getLogger(__name__) if not hasattr(vcx_messages_update_status, "cb"): logger.debug("vcx_messages_update_status: Creatin...
java
private Report getReport(ReportType reportType) { String type = null; String primaryColumn = null; Properties properties = new Properties(); if (reportType != null) { type = reportType.getType(); primaryColumn = reportType.getPrimaryColumn(); for (Prop...
python
def to_dictionary(self): """Serialize an object into dictionary form. Useful if you have to serialize an array of objects into JSON. Otherwise, if you call the :meth:`to_json` method on each object in the list and then try to dump the array, you end up with an array with one string."""...
python
def traverse_one(self, attribute, source, target, visitor): """ :param source: source data proxy :type source: instance of `DataTraversalProxy` or None :param target: target data proxy :type target: instance of `DataTraversalProxy` or None """ if __debug__: ...
java
@Deprecated public InputStream getInputStream(String bucketName, String key, Supplier<File> tempFileSupplier) throws AmazonServiceException, AmazonClientException, InterruptedException, IOException{ return readUtils.getInputStream(bucketName, key, tempFileSupplier); }
java
public static WxPayApiConfig putApiConfig(WxPayApiConfig wxPayApiConfig) { if (CFG_MAP.size() == 0) { CFG_MAP.put(DEFAULT_CFG_KEY, wxPayApiConfig); } return CFG_MAP.put(wxPayApiConfig.getAppId(), wxPayApiConfig); }
python
def result_group(group_id, failures=False, wait=0, count=None, cached=Conf.CACHED): """ Return a list of results for a task group. :param str group_id: the group id :param bool failures: set to True to include failures :param int count: Block until there are this many results in the group :para...
java
public static AbstractMessage duplicate( Message srcMessage ) throws JMSException { AbstractMessage msgCopy; // Internal type copy if (srcMessage instanceof AbstractMessage) msgCopy = ((AbstractMessage)srcMessage).copy(); else if (srcMessage instanceof TextMessage...
java
public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case MSG: return is_set_msg(); } throw new IllegalStateException(); }
java
public static <T> Set<Set<Node<T>>> compute(final Graph<T> graph) { final Set<Set<Node<T>>> connectedComponents = new LinkedHashSet<>(); final Set<Node<T>> unmarkedNodes = new LinkedHashSet<>(graph.nodes()); while (!unmarkedNodes.isEmpty()) { Set<Node<T>> connectedComp = new LinkedHashSet<>(); ...
python
def dropna(self, **kwargs): """Returns a new QueryCompiler with null values dropped along given axis. Return: a new DataManager """ axis = kwargs.get("axis", 0) subset = kwargs.get("subset", None) thresh = kwargs.get("thresh", None) how = kwargs.get("h...
python
def padDigitalData(self, dig_data, n): """Pad dig_data with its last element so that the new array is a multiple of n. """ n = int(n) l0 = len(dig_data) if l0 % n == 0: return dig_data # no need of padding else: ladd = n - (l0 % n) ...
python
def reload_input_system(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") reload = ET.Element("reload") config = reload input = ET.SubElement(reload, "input") system = ET.SubElement(input, "system") callback = kwargs.pop('callback'...
java
private void initialize() { this.setTitle(Constant.messages.getString("filter.changeua.title")); this.setContentPane(getJPanel()); if (Model.getSingleton().getOptionsParam().getViewParam().getWmUiHandlingOption() == 0) { this.setSize(375, 173); } this.setPreferredSize(new Dime...
python
def excludeSNPs(inPrefix, outPrefix, exclusionFileName): """Exclude some SNPs using Plink. :param inPrefix: the prefix of the input file. :param outPrefix: the prefix of the output file. :param exclusionFileName: the name of the file containing the markers to be excluded. ...
java
@Override public void destroy() throws Exception { String thisMethodName = CLASS_NAME + ".destroy()"; if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { SibTr.entry(tc, thisMethodName, ""); } // Destroy the ME's we created Enumeration meEnum = _...
python
def _update_mtime(self): """ Updates modif time """ try: self._mtime = os.path.getmtime(self.editor.file.path) except OSError: # file_path does not exists. self._mtime = 0 self._timer.stop() except (TypeError, AttributeError): #...
python
def __check_port(self, port): """check port status return True if port is free, False else """ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.bind((_host(), port)) return True except socket.error: return False fina...
java
public static Observable<String> stringConcat(Observable<String> src) { return toString(src.reduce(new StringBuilder(), new Func2<StringBuilder, String, StringBuilder>() { @Override public StringBuilder call(StringBuilder a, String b) { return a.append(b); } ...
python
def _GenerateChunk(self, length): """Generates data for a single chunk.""" while 1: to_read = min(length, self.RECV_BLOCK_SIZE) if to_read == 0: return data = self.rfile.read(to_read) if not data: return yield data length -= len(data)
java
@Override public void shutdown(ShutdownModeAmp mode) { if (! _lifecycle.toStopping()) { return; } _lifecycle.toDestroy(); OnShutdownMessage shutdownMessage = new OnShutdownMessage(this, mode, isSingle()); _queue.offer(shutdownMessage); // _queue.close(); /* ...
java
private static boolean isAssignableFrom(String genericD,String genericS,Class<?> classD,Class<?> classS,boolean isFirst, boolean isAddAllFunction,boolean isPutAllFunction){ try{ int dStartBracket = genericD.indexOf("<"); int sStartBracket = genericS.indexOf("<"); int dEndBracket = genericD.lastIndex...
python
def successors(self, node, exclude_compressed=True): """ Returns the list of successors of a given node Parameters ---------- node : str The target node exclude_compressed : boolean If true, compressed nodes are excluded from the successors list ...
java
protected String getOptionalAttributeValue(StartElement start, QName attributeName) { Attribute mapNameAttribute = start.getAttributeByName(attributeName); if (mapNameAttribute == null) { return null; } else { return mapNameA...
java
public void updateAsciiStream(int columnIndex, InputStream inputStream, long length) throws SQLException { checkUpdatable(columnIndex); if (inputStream == null) { parameterHolders[columnIndex - 1] = new NullParameter(ColumnType.BLOB); return; } parameterHolders[columnIndex - 1] = new S...
java
public String getKey(String tableName, String query, Object[] params) { return tableName + query + (params == null ? null : Arrays.asList(params).toString()); }
java
public List<GitlabJob> getProjectJobs(Integer projectId) { String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabJob.URL + PARAM_MAX_ITEMS_PER_PAGE; return retrieve().getAll(tailUrl, GitlabJob[].class); }
java
public Job copyTableId(String dataset, String tableName) throws BigQueryException { // [START bigquery_copy_table] TableId destinationId = TableId.of(dataset, tableName); JobOption options = JobOption.fields(JobField.STATUS, JobField.USER_EMAIL); Job job = table.copy(destinationId, options); // Wait...
java
public static String milliSecToString(final long mS) { final long rem_mS = (long)(mS % 1000.0); final long rem_sec = (long)((mS / 1000.0) % 60.0); final long rem_min = (long)((mS / 60000.0) % 60.0); final long hr = (long)(mS / 3600000.0); final String mSstr = zeroPad(Long.toString(rem_mS), 3); ...