language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static final KeyPressHandler getRegExKeyPressHandler(final String pregEx) { if (StringUtils.isEmpty(pregEx)) { return null; } RegExKeyPressHandler result = HandlerFactory.REG_EX_KEY_PRESS_HANDLER_MAP.get(pregEx); if (result == null) { result = new RegExKeyPressHandler(pregEx); } ...
python
def revert(self, strip=0, root=None): """ apply patch in reverse order """ reverted = copy.deepcopy(self) reverted._reverse() return reverted.apply(strip, root)
java
public void updateLastKnownStaleSequence(MetaDataContainer metaData, int partition) { long lastReceivedSequence; long lastKnownStaleSequence; do { lastReceivedSequence = metaData.getSequence(); lastKnownStaleSequence = metaData.getStaleSequence(); if (lastKno...
python
def delete(obj, key=None): """ Delete a single key if specified, or all env if key is none :param obj: settings object :param key: key to delete from store location :return: None """ client = StrictRedis(**obj.REDIS_FOR_DYNACONF) holder = obj.get("ENVVAR_PREFIX_FOR_DYNACONF") if key:...
python
def parse_section_extras_require(self, section_options): """Parses `extras_require` configuration file section. :param dict section_options: """ parse_list = partial(self._parse_list, separator=';') self['extras_require'] = self._parse_section_to_dict( section_option...
python
def get_child_fn(attrs, names, bases): """Returns a function from the child class that matches one of the names. Searches the child class's set of methods (i.e., the attrs dict) for all the functions matching the given list of names. If more than one is found, an exception is raised, if...
python
def get_vpc_dict(): """Returns dictionary of named VPCs {name: vpc} Assert fails if there's more than one VPC with same name.""" client = get_ec2_client() response = client.describe_vpcs() assert is_good_response(response) result = OrderedDict() ec2 = get_ec2_resource() for vpc_response in response['...
python
def plot_scalar(step, var, field=None, axis=None, set_cbar=True, **extra): """Plot scalar field. Args: step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData instance. var (str): the scalar field name. field (:class:`numpy.array`): if not None, it is plotted instea...
python
def render_template(process, template_string, context): """Render template using the specified expression engine.""" from resolwe.flow.managers import manager # Get the appropriate expression engine. If none is defined, do not evaluate # any expressions. expression_engine = process.requirements.get...
java
public void requestDelete(final String id) throws SDKException { CloseableHttpResponse response = null; HttpDelete httpDelete = null; checkToken(); try { log.debug("pathUrl: " + pathUrl); log.debug("id: " + pathUrl + "/" + id); // call the api here log.info("Executing delete on...
python
def compare(self, first, second, chamber, type='votes', congress=CURRENT_CONGRESS): """ See how often two members voted together in a given Congress. Takes two member IDs, a chamber and a Congress number. """ check_chamber(chamber) path = "members/{first}/{type}/{second}/...
java
private MjdbcSQLException translateJDBC4Exception(String reason, String SQLState, int vendorCode, SQLException cause) throws MjdbcException { MjdbcSQLException result = null; if (MappingUtils.objectAssignableTo(cause, "java.sql.SQLTransientException") == true) { if (MappingUtils.objectAssi...
python
def get_sos_step_steps(stmt): ''' Extract sos_step(x) from statement ''' opt_values = get_param_of_function( 'sos_step', stmt, extra_dict=env.sos_dict.dict()) for value in opt_values: if len(value) != 1: raise ValueError('sos_step only accept one and only one parameter') ...
java
public void paintFrame (Graphics2D g, int index, int x, int y) { _mirages[index].paint(g, x, y); }
python
def _get_block_transaction_data(db: BaseDB, transaction_root: Hash32) -> Iterable[Hash32]: """ Returns iterable of the encoded transactions for the given block header """ transaction_db = HexaryTrie(db, root_hash=transaction_root) for transaction_idx in itertools.count(): ...
java
public static void writeXML(Document xmldocument, String file) throws ParserConfigurationException, IOException { assert file != null : AssertMessages.notNullParameter(); try (FileOutputStream fos = new FileOutputStream(file)) { writeNode(xmldocument, fos); } }
python
def validate_indices(indices, n): """ Perform bounds-checking for an indexer. -1 is allowed for indicating missing values. Parameters ---------- indices : ndarray n : int length of the array being indexed Raises ------ ValueError Examples -------- >>> vali...
java
public ActiveTunnel[] getLocalForwardingTunnels() throws IOException { Vector<ActiveTunnel> v = new Vector<ActiveTunnel>(); String[] localForwardings = getLocalForwardings(); for (int i = 0; i < localForwardings.length; i++) { ActiveTunnel[] tmp = getLocalForwardingTunnels(localForwardings[i]); for (int x =...
python
def verify(self, h, sig): """ Return whether a signature is valid for hash h using this key. """ val = from_bytes_32(h) pubkey = self.public_pair() return self._generator.verify(pubkey, val, sigdecode_der(sig))
python
def set_prod_state(prod_state, device=None): ''' A function to set the prod_state in zenoss. Parameters: prod_state: (Required) Integer value of the state device: (Optional) Will use the grain 'fqdn' by default. CLI Example: salt zenoss.set_prod_state 1000 hostname ...
python
def consumer_initialize_task(processor, consumer_client, shard_id, cursor_position, cursor_start_time, cursor_end_time=None): """ return TaskResult if failed, or else, return InitTaskResult :param processor: :param consumer_client: :param shard_id: :param cursor_position: :param cursor_start...
python
def get_arg_parse(): """Parses the Command Line Arguments using argparse.""" # Create parser object: objParser = argparse.ArgumentParser() # Add argument to namespace -strCsvPrf results file path: objParser.add_argument('-strCsvPrf', required=True, metavar='/path/to/my_pr...
java
@Override public List<TextSpan> getSpans(Token token) { List<TextSpan> spans = new ArrayList<TextSpan>(); for (String type : connector.token2ItsTextSpans.keySet()) { Map<Token, TextSpan> tokToSpan = connector.token2ItsTextSpans.get(type); TextSpan span = tokToSpan.get(token);...
python
async def connect( cls, endpoint=None, uuid=None, username=None, password=None, cacert=None, bakery_client=None, loop=None, max_frame_size=None, retries=3, retry_backoff=10, ): ...
python
def establish_ssh(target=None, auto_trust=False, allow_agent=True, look_keys=True): r''' Establish a SSH connection to a remote host. It should be able to use SSH's config file Host name declarations. By default, will not automatically add trust for hosts, will use SSH agent and will try to load keys. ...
python
def encode_example(self, example_data): """See base class for details.""" np_dtype = np.dtype(self._dtype.as_numpy_dtype) # Convert to numpy if possible if not isinstance(example_data, np.ndarray): example_data = np.array(example_data, dtype=np_dtype) # Ensure the shape and dtype match if ...
java
@Override public void associateLog(DistributedRecoveryLog otherLog, boolean failAssociatedLog) { if (tc.isEntryEnabled()) Tr.entry(tc, "associateLog", new Object[] { otherLog, failAssociatedLog, this }); if (otherLog instanceof RecoveryLogImpl) _recoveryLog.associateLog(...
python
def retrieve_object(cache, template, indexes): """Retrieve an object from Redis using a pipeline. Arguments: template: a dictionary containg the keys for the object and template strings for the corresponding redis keys. The template string uses named string interpolation format....
python
def correlation_matrix(adata, name_list=None, groupby=None, group=None, n_genes=20, data='Complete', method='pearson', annotation_key=None): """Calculate correlation matrix. Calculate a correlation matrix for genes strored in sample annotation using :func:`~scanpy.api.tl.rank_genes_groups`. Parame...
java
public static Date parseDate(String date) { if (date == null) { return null; } try { return org.apache.commons.lang.time.DateUtils.parseDate(date, new String[] {DSP_DEFAULT_TIME_FORMAT}); } catch (ParseException e) { return null; } }
python
def authorization_denied_view(request): """Proxy for the view referenced in ``FANDJANGO_AUTHORIZATION_DENIED_VIEW``.""" authorization_denied_module_name = AUTHORIZATION_DENIED_VIEW.rsplit('.', 1)[0] authorization_denied_view_name = AUTHORIZATION_DENIED_VIEW.split('.')[-1] authorization_denied_module = ...
java
protected void checkThreshold (final int nCount) throws IOException { if (!m_bThresholdExceeded && (m_nWritten + nCount > m_nThreshold)) { m_bThresholdExceeded = true; onThresholdReached (); } }
python
def format_jid_instance(jid, job): ''' Format the jid correctly ''' ret = format_job_instance(job) ret.update({'StartTime': jid_to_time(jid)}) return ret
java
@Override public synchronized Reader executeCommandReader(String command) throws SshException, IOException { if (!isConnected()) { throw new IllegalStateException("Not connected!"); } try { Channel channel = connectSession.openChannel("exec"); ((ChannelExe...
python
def parse_date(datestr): """ Parse a date expression into a tuple of: (start_date, span_type, span_format) Arguments: datestr -- A date specification, in the format of YYYY-MM-DD (dashes optional) """ match = re.match( r'([0-9]{4})(-?([0-9]{1,2}))?(-?([0-9]{1,2}))?(_w)?$', dat...
python
def unsubscribe(self): """Unsubscribes this subscriber from the associated list.""" body = { "EmailAddress": self.email_address} response = self._post("/subscribers/%s/unsubscribe.json" % self.list_id, json.dumps(body))
python
def chgrp(path, group): ''' Change the group of a file path path to the file or directory group group owner CLI Example: .. code-block:: bash salt '*' file.chgrp /etc/passwd root ''' path = os.path.expanduser(path) user = get_user(path) return chown(...
python
def reflect(cls, X, **kwargs): """Reflect is for visitors where you are exposing some information about the types reachable from a starting type to an external system. For example, a front-end, a REST URL router and documentation framework, an avro schema definition, etc. X can ...
java
public static String encodeHeaderParameter(String name, String value) { name = name.toLowerCase(Locale.US); // value := token / quoted-string if (isToken(value)) { return name + "=" + value; } else { return name + "=" + quote(value); } }
python
def read_yaml(self, filename): ''' Reads and parses a YAML file and returns the content. ''' with open(filename, 'r') as f: d = re.sub(r'\{\{ *([^ ]+) *\}\}', r'\1', f.read()) y = yaml.safe_load(d) return y if y else {}
java
public static AssetVersionCreator creator(final String pathServiceSid, final String pathAssetSid, final String path, final AssetVersion.Visibility visibility) { return new...
python
def ensure_one_opt(opt, parser, opt_list): """ Check that one and only one in the opt_list is defined in opt Parameters ---------- opt : object Result of option parsing parser : object OptionParser instance. opt_list : list of strings """ the_one = None for name in...
python
def str_extractall(arr, pat, flags=0): r""" For each subject string in the Series, extract groups from all matches of regular expression pat. When each subject string in the Series has exactly one match, extractall(pat).xs(0, level='match') is the same as extract(pat). .. versionadded:: 0.18.0 ...
python
def stop(self): """Stop serving. Always call this to clean up after yourself.""" self._stopped = True threads = [self._accept_thread] threads.extend(self._server_threads) self._listening_sock.close() for sock in list(self._server_socks): try: s...
java
public void marshall(AdminForgetDeviceRequest adminForgetDeviceRequest, ProtocolMarshaller protocolMarshaller) { if (adminForgetDeviceRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(adminFo...
java
private void addFieldElement(ECFieldElement v) { final byte[] p = BigIntegers.asUnsignedByteArray(this.curveLength, v.toBigInteger()); this.digest.update(p, 0, p.length); }
python
def _error_to_string(self, error_id): """Returns an error string from libiperf :param error_id: The error_id produced by libiperf :rtype: string """ strerror = self.lib.iperf_strerror strerror.restype = c_char_p return strerror(error_id).decode('utf-8')
python
def on_before_publish_insert_request_id_header(headers, **kwargs): """ This function is meant to be used as signal processor for "before_task_publish". :param Dict headers: The headers of the message :param kwargs: Any extra keyword arguments """ if _CELERY_X_HEADER not in headers: reque...
python
def search(table: LdapObjectClass, query: Optional[Q] = None, database: Optional[Database] = None, base_dn: Optional[str] = None) -> Iterator[LdapObject]: """ Search for a object of given type in the database. """ fields = table.get_fields() db_fields = { name: field for name, fie...
java
private void rebuildSimpleTab() { m_form.removeGroup(CmsPropertyPanel.TAB_SIMPLE); CmsPropertyPanel panel = ((CmsPropertyPanel)m_form.getWidget()); panel.clearTab(CmsPropertyPanel.TAB_SIMPLE); if (m_handler.hasEditableName()) { m_form.addField(CmsPropertyPanel.TAB_SIMPLE, cr...
java
@Override public int getChildCount(final List<Integer> row) { // Should not occur if (row == null || row.isEmpty()) { return 0; } // No expandable levels defined, so always 0 if (levels.size() == 1) { return 0; } // Check iterations if (isIterateFirstLevel() && getMaxIterations() > -1 && row.si...
python
def removed(name, ruby=None, user=None, gem_bin=None): ''' Make sure that a gem is not installed. name The name of the gem to uninstall gem_bin : None Full path to ``gem`` binary to use. ruby : None If RVM or rbenv are installed, the ruby version and gemset to use. ...
java
@Api public void setMapType(MapType type) { this.type = type; if (googleMap != null) { setMapType(googleMap, type.toString()); } }
java
public static String formatUnknownKey(String keyName) { StringBuffer buf = new StringBuffer(64); buf.append(UNKNOWN_KEY_EXTENSION); buf.append(" "); buf.append(keyName); buf.append(" "); buf.append(UNKNOWN_KEY_EXTENSION); return buf.toString(); }
python
def is_raster_y_inverted(layer): """Check if the raster is upside down, ie Y inverted. See issue : https://github.com/inasafe/inasafe/issues/4026 :param layer: The layer to test. :type layer: QgsRasterLayer :return: A boolean to know if the raster is correct or not. :rtype: bool """ i...
python
def load_lsdsng(filename): """Load a Project from a ``.lsdsng`` file. :param filename: the name of the file from which to load :rtype: :py:class:`pylsdj.Project` """ # Load preamble data so that we know the name and version of the song with open(filename, 'rb') as fp: preamble_data = b...
python
def _serialize_pages(self): """ Return a JSON API compliant pagination links section If the paginator has a value for a given link then this method will also add the same links to the response objects `link` header according to the guidance of RFC 5988. Falcon has a nat...
python
def smooth(x, y, degree=1, logx=False, logy=False): """Smooth y-values and return new x, y pair. :param x,y: data values :param degree: degree of smoothing Smooth data by using a recursive linear interpolation technique. For degree = 0, return the original values. For degree = 1, generate a ...
java
public boolean canPing() { val uidPsw = getClass().getSimpleName(); for (val server : this.servers) { LOGGER.debug("Attempting to ping RADIUS server [{}] via simulating an authentication request. If the server responds " + "successfully, mock authentication will fail correctl...
python
def get_witnesses(self, name='*'): """Returns a generator supplying `WitnessText` objects for each work in the corpus. :rtype: `generator` of `WitnessText` """ for filepath in glob.glob(os.path.join(self._path, name, '*.txt')): if os.path.isfile(filepath): ...
java
public void send(StDatapoint datapoint) { StDatapointValidator.validate(datapoint); sender.send(Collections.singletonList(datapoint)); }
java
@CheckReturnValue public AuditableRestAction<Void> ban(Member member, int delDays) { return ban(member, delDays, null); }
python
def if_then(self, classical_reg, if_program, else_program=None): """ If the classical register at index classical reg is 1, run if_program, else run else_program. Equivalent to the following construction: .. code:: IF [c]: instrA... ELSE:...
python
def _retransmit(self, transaction, message, future_time, retransmit_count): """ Thread function to retransmit the message in the future :param transaction: the transaction that owns the message that needs retransmission :param message: the message that needs the retransmission task ...
java
private void processModifiersAndVariablesOfFieldDeclaration( FieldDeclaration fieldDeclaration, FieldMetadata arrayTypeFieldMetadata ) { processModifiersOfFieldDeclaration(fieldDeclaration, arrayTypeFieldMetadata); processVariablesOfVariab...
java
public static QueryColumn toQueryColumn(Object o) throws PageException { if (o instanceof QueryColumn) return (QueryColumn) o; throw new CasterException(o, "querycolumn"); }
java
public static void glBlendColor(float r, float g, float b, float a) { checkContextCompatibility(); nglBlendColor(r, g, b, a); }
java
@Override public void shutdown() { // Since Aeron's poll isn't blocking, all we need is just special flag runner.set(false); try { threadA.join(); if (threadB != null) threadB.join(); } catch (Exception e) { // } Cl...
java
@Override public void saveChanges() { BatchOperation saveChangeOperation = new BatchOperation(this); try (BatchCommand command = saveChangeOperation.createRequest()) { if (command == null) { return; } if (noTracking) { throw new I...
java
private static boolean matchInf(byte[] str, byte firstchar, int start, int end) { final int len = end - start; // The wonders of unicode. The infinity symbol \u221E is three bytes: if(len == 3 && firstchar == -0x1E && str[start + 1] == -0x78 && str[start + 2] == -0x62) { return true; } if((len...
java
public void resolveType() { if (getTypeStyle() == null) { setTypeStyle(""); } final String fieldType = getFieldType(); String generics = ""; if (fieldType.contains("<")) { generics = fieldType.substring(fieldType.indexOf('<')); } if (getTyp...
python
def PartialDynamicSystem(self, ieq, variable): """ returns dynamical system blocks associated to output variable """ if ieq == 0: # w2=Rw1 if variable == self.physical_nodes[0].variable: # w1=w2/R return[Gain(self.physical_nodes[1]....
python
def _NormalizedVolumeIdentifiers( self, volume_system, volume_identifiers, prefix='v'): """Normalizes volume identifiers. Args: volume_system (VolumeSystem): volume system. volume_identifiers (list[int|str]): allowed volume identifiers, formatted as an integer or string with prefix....
java
public void removeChild(int index) { N child = children.remove(index); child.setParent(null); }
python
def _extract_text_and_child_element_list(minidom_node): """Returns a pair of the "child" content of minidom_node: the first element of the pair is a concatenation of the text content the second element is a list of non-text nodes. The string concatenation strips leading and trailing whitespace ...
python
def off(self): """Send an OFF message to device group.""" off_command = ExtendedSend(self._address, COMMAND_LIGHT_OFF_0X13_0X00, self._udata) off_command.set_checksum() self._send_method(off_command, self._off_message_...
python
def dbmin50years(self, value=None): """ Corresponds to IDD Field `dbmin50years` 50-year return period values for minimum extreme dry-bulb temperature Args: value (float): value for IDD Field `dbmin50years` Unit: C if `value` is None it will not be ch...
python
def add_stock(self, product_id, sku_info, quantity): """ 增加库存 :param product_id: 商品ID :param sku_info: sku信息,格式"id1:vid1;id2:vid2",如商品为统一规格,则此处赋值为空字符串即可 :param quantity: 增加的库存数量 :return: 返回的 JSON 数据包 """ return self._post( 'merchant/stock/add'...
python
def aq_esc_telemetry_encode(self, time_boot_ms, seq, num_motors, num_in_seq, escid, status_age, data_version, data0, data1): ''' Sends ESC32 telemetry data for up to 4 motors. Multiple messages may be sent in sequence when system has > 4 motors. Data is de...
java
private void not() { tq.consume(":not"); String subQuery = tq.chompBalanced('(', ')'); Validate.notEmpty(subQuery, ":not(selector) subselect must not be empty"); evals.add(new StructuralEvaluator.Not(parse(subQuery))); }
python
def multiupload(self, filename, hosts): """Upload file to multiple hosts simultaneously The upload will be attempted for each host until the optimal file redundancy is achieved (a percentage of successful uploads) or the host list is depleted. :param filename: The filename of t...
java
public String uploadSliceFile(UploadSliceFileRequest request) throws AbstractCosException { request.check_param(); String controlRet = uploadSliceControl(request); JSONObject controlRetJson = new JSONObject(controlRet); // 如果控制分片已经出错, 则返回 if (controlRetJson.getInt(ResponseBodyKey.CODE) != 0) { return contr...
python
def values(self): """Return the `list representation`_ of the binary tree. .. _list representation: https://en.wikipedia.org/wiki/Binary_tree#Arrays :return: List representation of the binary tree, which is a list of node values in breadth-first order starting from the ...
python
def get_instance(self, payload): """ Build an instance of TriggerInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.usage.trigger.TriggerInstance :rtype: twilio.rest.api.v2010.account.usage.trigger.TriggerInstance """ ...
python
def press(keys, presses=1, interval=0.0, pause=None, _pause=True): """Performs a keyboard key press down, followed by a release. Args: key (str, list): The key to be pressed. The valid names are listed in KEYBOARD_KEYS. Can also be a list of such strings. presses (integer, optiional): the num...
python
def resize_canvas(self, height=400, width=400): """ Function for the user to resize the internal Canvas widget if desired. :param height: new height in pixels :type height: int :param width: new width in pixels :type width: int """ self._canvas.co...
java
public boolean includesAny(Tech... techs) { if (techs == null || techs.length == 0) { return false; } for (Tech tech : techs) { if (includes(tech)) { return true; } } return false; }
java
public static authenticationradiuspolicy_systemglobal_binding[] get(nitro_service service, String name) throws Exception{ authenticationradiuspolicy_systemglobal_binding obj = new authenticationradiuspolicy_systemglobal_binding(); obj.set_name(name); authenticationradiuspolicy_systemglobal_binding response[] = (a...
python
def _offline_fcp_device(self, fcp, target_wwpn, target_lun, multipath): """sles offline zfcp. sampe to all rhel distro.""" device = '0.0.%s' % fcp # disk config disk_config = '/sbin/zfcp_disk_configure ' +\ '%(device)s %(wwpn)s %(lun)s 0' %\ {'...
python
def hdel(self, name, *keys): """ Delete one or more hash field. :param name: str the name of the redis key :param keys: on or more members to remove from the key. :return: Future() """ with self.pipe as pipe: m_encode = self.memberparse.encode ...
python
def _str_parser(string): """ return method by the length of string :param string: string :return: method """ if not any(c.isalpha() for c in string): _string = string[:19] _length = len(_string) if _length > 10: return B...
python
def overlay(repository, files, version, debug=False): """ Overlay files from the specified repository/version into the given directory and return None. :param repository: A string containing the path to the repository to be extracted. :param files: A list of `FileConfig` objects. :param ve...
python
def _json_data(x, extraneous): """This function calls a json_json method, if the type has one, otherwise calls back into to_json(). It also check whether the method takes an 'extraneous' argument and passes that through if possible.""" if type(x) in has_json_data and has_json_data[type(x)]: if...
java
public IRenderingElement generateDiagram(T object) { ElementGroup diagram = new ElementGroup(); for (IGenerator<T> generator : this.generators) { diagram.add(generator.generate(object, this.rendererModel)); } return diagram; }
python
def loaders(self): # pragma: no cover """Return available loaders""" if self.LOADERS_FOR_DYNACONF in (None, 0, "0", "false", False): self.logger.info("No loader defined") return [] if not self._loaders: for loader_module_name in self.LOADERS_FOR_DYNACONF: ...
java
private static LineString linearZInterpolation(LineString lineString) { double startz = lineString.getStartPoint().getCoordinate().z; double endz = lineString.getEndPoint().getCoordinate().z; if (Double.isNaN(startz) || Double.isNaN(endz)) { return lineString; } else { ...
java
@Override public ClientBuilder keyStore(final KeyStore keyStore, final String password) { this.clientKeyStore = keyStore; this.clientPrivateKeyPassword = password; return this; }
python
def get_seconds_until_next_day(now=None): """ Returns the number of seconds until the next day (utc midnight). This is the long-term rate limit used by Strava. :param now: A (utc) timestamp :type now: arrow.arrow.Arrow :return: the number of seconds until next day, as int """ if now is None:...
python
def convert_data_array(arr, filter_func=None, converter_func=None): '''Filter and convert any given data array of any dtype. Parameters ---------- arr : numpy.array Data array of any dtype. filter_func : function Function that takes array and returns true or false for each i...
java
public void offerStatement(int stmtHash, int offset, ByteBuffer psetBuffer) { m_inputCRC.update(stmtHash); m_inputCRC.updateFromPosition(offset, psetBuffer); if (m_hashCount < MAX_HASHES_COUNT) { m_hashes[m_hashCount] = stmtHash; m_hashes[m_hashCount + 1] = (int) m_input...