language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def _get_tau_vector(self, tau_mean, tau_std, imt_list): """ Gets the vector of mean and variance of tau values corresponding to the specific model and returns them as dictionaries """ self.magnitude_limits = MAG_LIMS_KEYS[self.tau_model]["mag"] self.tau_keys = MAG_LIMS_KE...
python
def _remove_dep(self, dep): """ Decrement the reference count for *dep*. If the reference count reaches 0, then the dependency is removed and its *changed* event is disconnected. """ refcount = self._deps[dep] if refcount == 1: self._deps.pop(dep) ...
python
def times(self, other): """ Multiply a matrix by another one. Other matrix must be a numpy array, a scalar, or another matrix in local mode. Parameters ---------- other : Matrix, scalar, or numpy array A matrix to multiply with """ if...
java
@Override public Mono<MongoSession> findById(String id) { return findSession(id) // .map(document -> convertToSession(this.mongoSessionConverter, document)) // .filter(mongoSession -> !mongoSession.isExpired()) // .switchIfEmpty(Mono.defer(() -> this.deleteById(id).then(Mono.empty()))); }
java
public void suspend(final byte[] message) { synchronized (this.heartBeatManager) { if (this.currentStatus.isNotRunning()) { LOG.log(Level.WARNING, "Trying to suspend a task that is in state: {0}. Ignoring.", this.currentStatus.getState()); } else { try { this.suspen...
python
def get_objective_sequencing_session(self, proxy): """Gets the session for sequencing objectives. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.learning.ObjectiveSequencingSession) - an ``ObjectiveSequencingSession`` raise: NullArgument - ``proxy`` is ``null``...
java
@Override public JsonElement serialize(BoundingBox src, Type typeOfSrc, JsonSerializationContext context) { JsonArray bbox = new JsonArray(); // Southwest Point point = src.southwest(); List<Double> unshiftedCoordinates = CoordinateShifterManager.getCoordinateShifter().unshiftPoint(point)...
python
def get_parent_ids(self): """Gets the parents of this node. return: (osid.id.IdList) - the parents of this node *compliance: mandatory -- This method must be implemented.* """ id_list = [] from ..id.objects import IdList for parent_node in self._my_map['parentNo...
java
public boolean writeToURI(Node nodeArg, String uri) throws LSException { // If nodeArg is null, return false. Should we throw and LSException instead? if (nodeArg == null ) { return false; } // Obtain a reference to the serializer to use Serializer serializer = fXML...
java
@Nullable public static String getClassLocalName (@Nullable final String sClassName) { if (sClassName == null) return null; final int nIndex = sClassName.lastIndexOf ('.'); return nIndex == -1 ? sClassName : sClassName.substring (nIndex + 1); }
python
def response_rate_text(records): """ The response rate of the user (between 0 and 1). Considers text-conversations which began with an incoming text. The response rate is the fraction of such conversations in which the user sent a text (a response). The following sequence of messages defines f...
java
protected String className(ClassType t, boolean longform, Locale locale) { Symbol sym = t.tsym; if (sym.name.length() == 0 && (sym.flags() & COMPOUND) != 0) { StringBuilder s = new StringBuilder(visit(t.supertype_field, locale)); for (List<Type> is = t.interfaces_field; is.nonEmp...
python
def sponsor_or_site(self, value): """Set Originator with validation of input""" if value not in Comment.VALID_SPONSOR_OR_SITE_RESPONSES: raise AttributeError("%s sponsor_or_site value of %s is not valid" % (self.__class__.__name__, ...
java
private static void seedData(PersistenceManager manager) throws OnyxException { // Create a call log for area code (555) CellPhone myPhoneNumber = new CellPhone(); myPhoneNumber.setCellPhoneNumber("(555) 303-2322"); myPhoneNumber.setAreaCode(555); manager.saveEntity(myPhoneNu...
python
def fetchExternalUpdates(self): """ !Experimental! Calls out to the client code requesting seed values to use in the UI !Experimental! """ seeds = seeder.fetchDynamicProperties( self.buildSpec['target'], self.buildSpec['encoding'] ...
java
public Map<Object,Object> singletonMap(Object key, Object value) throws JSONObjectException { return start().put(key, value).build(); }
python
def filter_resource(self, resource_name, field_name, field_value, result_handler=ONE_RESULT): """ :return: The resource (as json), or None """ return self.multi_filter_resource(resource_name, {field_name: field_value}, ...
java
public OvhGameMitigationRule ip_game_ipOnGame_rule_POST(String ip, String ipOnGame, OvhRange<Long> ports, OvhGameMitigationRuleProtocolEnum protocol) throws IOException { String qPath = "/ip/{ip}/game/{ipOnGame}/rule"; StringBuilder sb = path(qPath, ip, ipOnGame); HashMap<String, Object>o = new HashMap<String, Ob...
python
def deep_copy(self): """ Returns a deep copy. """ return ContinuousColumn(self.arr, metadata=self.metadata, missing_id=self._missing_id, weights=self.weights)
python
def _get_recursive_dependancies(self, dependencies_map, sourcepath, recursive=True): """ Return all dependencies of a source, recursively searching through its dependencies. This is a common method used by ``children`` and ``parents`` methods. ...
java
public <T> void registerMethods(final Class<T> cls, String toStringMethodName, String fromStringMethodName) { if (cls == null) { throw new IllegalArgumentException("Class must not be null"); } if (toStringMethodName == null || fromStringMethodName == null) { throw ne...
python
def append_json( self, obj: Any, headers: Optional['MultiMapping[str]']=None ) -> Payload: """Helper to append JSON part.""" if headers is None: headers = CIMultiDict() return self.append_payload(JsonPayload(obj, headers=headers))
python
def authenticate(self): """Check the user authentication.""" endpoint = os.path.join(self.config.get('napps', 'api'), 'auth', '') username = self.config.get('auth', 'user') password = getpass("Enter the password for {}: ".format(username)) response = requests.get(endpoint, auth=(...
java
public static Button createAppIconButton(I_CmsWorkplaceAppConfiguration appConfig, Locale locale) { return createIconButton( appConfig.getName(locale), appConfig.getHelpText(locale), appConfig.getIcon(), appConfig.getButtonStyle()); }
java
private void clearMappingRegistry(Object o, Class<?> clazz_AbstractHandlerMethodMapping) { if (debug) { System.out.println("SPRING_PLUGIN: clearing out mapping registry..."); } Object mappingRegistryInstance = null; try { Field field_mappingRegistry = clazz_AbstractHandlerMethodMapping.getDeclaredField("m...
java
public final BELScriptWalker.function_return function() throws RecognitionException { BELScriptWalker.function_return retval = new BELScriptWalker.function_return(); retval.start = input.LT(1); CommonTree root_0 = null; CommonTree _first_0 = null; CommonTree _last = null; ...
python
def convert_timedelta(duration): """ Summary: Convert duration into component time units Args: :duration (datetime.timedelta): time duration to convert Returns: days, hours, minutes, seconds | TYPE: tuple (integers) """ days, seconds = duration.days, duration.seconds ...
java
private void removeFromIndices(T object) { for (FieldIndex<T, ?> fieldValue : mIndices.values()) { fieldValue.remove(object); } }
python
def listar_por_equip(self, equip_id): """Lista todos os ambientes por equipamento especifico. :return: Dicionário com a seguinte estrutura: :: {'ambiente': {'id': < id_ambiente >, 'link': < link >, 'id_divisao': < id_divisao >, 'nome_divisao': <...
python
def scale_degree_to_semitone(scale_degree): r"""Convert a scale degree to semitone. Parameters ---------- scale degree : str Spelling of a relative scale degree, e.g. 'b3', '7', '#5' Returns ------- semitone : int Relative semitone of the scale degree, wrapped to a single o...
java
protected void loadClass(List<Class> classes, ClassLoader cld, String className) { try { classes.add(cld.loadClass(className)); } catch (NoClassDefFoundError e) { log().log(Level.WARNING, "error loading class " + className, e); } ...
python
def hostinterface_create(hostid, ip_, dns='', main=1, if_type=1, useip=1, port=None, **kwargs): ''' .. versionadded:: 2016.3.0 Create new host interface .. note:: This function accepts all standard host group interface: keyword argument names differ depending on your zabbix version, se...
java
@Override public Request<DescribeVolumeStatusRequest> getDryRunRequest() { Request<DescribeVolumeStatusRequest> request = new DescribeVolumeStatusRequestMarshaller().marshall(this); request.addParameter("DryRun", Boolean.toString(true)); return request; }
java
public static boolean startsWithPrefix(final String input) { boolean ret = false; if (input != null) { ret = input.toLowerCase().startsWith(PREFIX_BIGINT_DASH_CHECKSUM); } else { ret = false; } return ret; }
java
public Integer delInfoByBizIdService(String bizId,String tableName,String bizCol){ Integer filterViewRet=filterView(tableName,new HashMap(),bizId,bizCol,TYPE_DEL_BIZID); if(filterViewRet!=null && filterViewRet>0){ return filterViewRet; } Integer retStatus=getInnerDao().delObjByBizId(tableName,bi...
python
def pvector_field(item_type, optional=False, initial=()): """ Create checked ``PVector`` field. :param item_type: The required type for the items in the vector. :param optional: If true, ``None`` can be used as a value for this field. :param initial: Initial value to pass to factory if no v...
python
def gengraphs(pth, nopyfftw): """ Generate call graph images when necessary. Parameter pth is the path to the directory in which images are to be created. Parameter nopyfftw is a flag indicating whether it is necessary to avoid using pyfftw. """ srcmodflt = '^sporco.admm' srcqnmflt = r'^((?...
java
public I_CmsPropertyProvider getPropertyProvider(String key) { if (key.startsWith(PROPERTY_PREFIX_DYNAMIC)) { key = key.substring(PROPERTY_PREFIX_DYNAMIC.length()); } for (I_CmsPropertyProvider provider : m_propertyProviders) { if (provider.getName().equals(key)) { ...
java
public void setItemText(int index, String text) { index += getIndexOffset(); listBox.setItemText(index, text); reload(); }
python
def colormapped_bedfile(self, genome, cmap=None): """ Create a BED file with padj encoded as color Features will be colored according to adjusted pval (phred transformed). Downregulated features have the sign flipped. Parameters ---------- cmap : matplotlib col...
java
@CanIgnoreReturnValue // TODO(kak): Consider removing this? @Nullable public static <T> T getOnlyElement(Iterator<? extends T> iterator, @Nullable T defaultValue) { return iterator.hasNext() ? getOnlyElement(iterator) : defaultValue; }
java
public HttpRequest buildPostRequest(GenericUrl url, HttpContent content) throws IOException { return buildRequest(HttpMethods.POST, url, content); }
python
def set_index(self, schema, name, fields, **index_options): """ add an index to the table schema -- Schema() name -- string -- the name of the index fields -- array -- the fields the index should be on **index_options -- dict -- any index options that might be useful to ...
python
def mark_quoted_strings(sql): """Mark all quoted strings in the SOQL by '@' and get them as params, with respect to all escaped backslashes and quotes. """ # pattern of a string parameter (pm), a char escaped by backslash (bs) # out_pattern: characters valid in SOQL pm_pattern = re.compile(r"'[^...
java
public boolean setCurrentConfiguration(CmsGitConfiguration configuration) { if ((null != configuration) && configuration.isValid()) { m_currentConfiguration = configuration; return true; } return false; }
java
public static long reverseBits(final byte value, final JBBPBitNumber bits) { return JBBPUtils.reverseBitsInByte(value) >>> (8 - bits.getBitNumber()) & bits.getMask(); }
java
static String[] splitOnTokens(final String text) { // used by wildcardMatch // package level so a unit test may run on this if (text.indexOf('?') == NOT_FOUND && text.indexOf('*') == NOT_FOUND) { return new String[] { text }; } final char[] array = text.toCh...
java
public static Type parameterizedType(Object object) { if (object != null) { Type type = object.getClass().getGenericSuperclass(); if (type instanceof ParameterizedType) { return ((ParameterizedType) type).getActualTypeArguments()[0]; } } return Object.class; }
python
def load_xml_generator_configuration(configuration, **defaults): """ Loads CastXML or GCC-XML configuration. Args: configuration (string|configparser.ConfigParser): can be a string (file path to a configuration file) or instance of :class:`configparser.ConfigParser`. ...
java
public Factor getMarginalEntries(int spanStart, int spanEnd) { return getOutsideEntries(spanStart, spanEnd).product(getInsideEntries(spanStart, spanEnd)); }
python
def delete(self, collector_id=None): """Delete a collector from inventory. Args: collector_id (int): id of collector (optional) """ cid = self.collector_id if collector_id: cid = collector_id # param to delete id url = '{0}/{1}'.format(s...
python
def _compute_v1_factor(self, imt): """ Compute and return v1 factor, equation 6, page 77. """ if imt.name == "SA": t = imt.period if t <= 0.50: v1 = 1500.0 elif t > 0.50 and t <= 1.0: v1 = np.exp(8.0 - 0.795 * np.log(t /...
java
public static <T> T getInstance(Class<T> clazz) { try { Constructor<T> constructor = clazz.getConstructor(); ReflectUtil.allowAccess(constructor); return constructor.newInstance(); } catch (Exception e) { throw new ReflectException("获取类实例异常,可能是没有默认无参构造器", ...
python
def _get_local_users(self, disabled=None): ''' Return all known local accounts to the system. ''' users = dict() path = '/etc/passwd' with salt.utils.files.fopen(path, 'r') as fp_: for line in fp_: line = line.strip() if ':' not...
java
InputStream head(URI uri) { HttpConnection connection = Http.HEAD(uri); return executeToInputStream(connection); }
java
public void marshall(GetLinkAttributesRequest getLinkAttributesRequest, ProtocolMarshaller protocolMarshaller) { if (getLinkAttributesRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(getLink...
python
def get_network_instances(self, name=''): """get_network_instances implementation for EOS.""" output = self._show_vrf() vrfs = {} all_vrf_interfaces = {} for vrf in output: if (vrf.get('route_distinguisher', '') == "<not set>" or vrf.get('route_di...
java
@NonNull public SelfT withKeyspace(@Nullable String keyspaceName) { return withKeyspace(keyspaceName == null ? null : CqlIdentifier.fromCql(keyspaceName)); }
python
def alerts(self): """returns the alerts list. If samecode(s) are specified when the WeatherAlerts object is created, this will only return alerts for those samecodes. If no samecodes were given, it'll return all alerts for the state if one was specified otherwise for the entire U.S. """ ...
java
public static byte[] hex2byte(String hex) { byte[] ret = new byte[8]; byte[] tmp = hex.getBytes(); for (int i = 0; i < 8; i++) { ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]); } return ret; }
python
def create(self, label, status=None, master=None): """ Create an Identity :param label: The label to give this new identity :param status: The status of this identity. Default: 'active' :param master: Represents whether this identity is a master. Default: Fal...
python
def _add_new_state(self, *event, **kwargs): """Triggered when shortcut keys for adding a new state are pressed, or Menu Bar "Edit, Add State" is clicked. Adds a new state only if the graphical editor is in focus. """ if react_to_event(self.view, self.view.editor, event): sta...
python
def generate_parsers(config, paths): """ Generate parser for all `paths`. Args: config (dict): Original configuration dictionary used to get matches for unittests. See :mod:`~harvester.autoparser.conf_reader` for details. paths (dict): Output fr...
python
def lint(self, commit): """ Lint the last commit in a given git context by applying all ignore, title, body and commit rules. """ LOG.debug("Linting commit %s", commit.sha or "[SHA UNKNOWN]") LOG.debug("Commit Object\n" + ustr(commit)) # Apply config rules for rule in self.confi...
python
def proxy_image(self, s=0, c=0, z=0, t=0): """Return a :class:`jicimagelib.image.MicroscopyImage` instance. :param s: series :param c: channel :param z: zslice :param t: timepoint :returns: :class:`jicimagelib.image.MicroscopyImage` """ for proxy_...
java
static public Tokenizer getTokenizer(String filename) throws IOException { if(filename.toLowerCase().endsWith("xml")) { return new XmlTokenizer(filename); } else { return new BinaryTokenizer(filename); } }
python
def flatwrite(cls, table, order=None, header=None, output="table", sort_keys=True, show_none="", sep="." ): """ writes the information given in the table :param table: th...
java
@Override protected void onFinishInflate() { super.onFinishInflate(); bind(); initializeBackground(); initializeTurnLaneRecyclerView(); initializeInstructionListRecyclerView(); initializeAnimations(); initializeStepListClickListener(); initializeButtons(); ImageCreator.getInstance(...
python
def calc_scaled_res(self, screen_res, image_res): """Calculate appropriate texture size. Calculate size or required texture so that it will fill the window, but retains the movies original aspect ratio. Parameters ---------- screen_res : tuple Display window size/Resolution image_res : tuple ...
java
public void marshall(ProjectArtifacts projectArtifacts, ProtocolMarshaller protocolMarshaller) { if (projectArtifacts == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(projectArtifacts.getType(), TYP...
python
def query(self, variables, evidence=None, joint=True): """ Query method using belief propagation. Parameters ---------- variables: list list of variables for which you want to compute the probability evidence: dict a dict key, value pair as {var:...
java
public synchronized static Bitmap load(InputStream is, int width, int height) { BitmapFactory.Options opt = null; try { opt = new BitmapFactory.Options(); if (width > 0 && height > 0) { if (is.markSupported()) { is.mark(is.available()); ...
java
@GwtIncompatible("java.util.ResourceBundle") public static String getReleaseVersion() { ResourceBundle config = ResourceBundle.getBundle(CONFIG_RESOURCE); return config.getString("compiler.version"); }
python
def delete_whitespaces(self, arg): """Removes newlines, tabs and whitespaces at the beginning, the end and if there is more than one. :param arg: A string, the string which shell be cleaned :return: A string, the cleaned string """ # Deletes whitespaces after a newline a...
java
public static DMatrix4 extractRow( DMatrix4x4 a , int row , DMatrix4 out ) { if( out == null) out = new DMatrix4(); switch( row ) { case 0: out.a1 = a.a11; out.a2 = a.a12; out.a3 = a.a13; out.a4 = a.a14; break; ...
java
private void createDebug() { frame = new JFrame("Smack Debug Window -- " + connection.getXMPPServiceDomain() + ":" + connection.getPort()); // Add listener for window closing event frame.addWindowListener(new WindowAdapter() { @Override public void window...
python
def _make_resource_from_inline(reference): """Makes an ``models.Resource`` from a ``models.Reference`` of type INLINE. That is, a data: uri""" uri = DataURI(reference.uri) data = io.BytesIO(uri.data) mimetype = uri.mimetype res = Resource('dummy', data, mimetype) res.id = res.filename ...
python
def independent_interdomain_conditional(Kmn, Kmm, Knn, f, *, full_cov=False, full_output_cov=False, q_sqrt=None, white=False): """ The inducing outputs live in the g-space (R^L). Interdomain conditional calculation. :param Kmn: M x L x N x P :param Kmm: L x M...
python
def require(request): """ Raise :exc:`AssertionError` if gtkmvc3 version is not compatible. *request* a dotted string or iterable of string or integers representing the minimum version you need. :: require("1.0") require(("1", "2", "2")) require([1,99,0]) .. note:: For hist...
java
@Override public JsonElement serialize(CMAEntry src, Type type, JsonSerializationContext context) { JsonObject fields = new JsonObject(); for (Map.Entry<String, LinkedHashMap<String, Object>> field : src.getFields().entrySet()) { LinkedHashMap<String, Object> value = field.getValue(); if (value ==...
python
def get_spaces(**kwargs): """ Return a list of reservations matching the passed filter. Supported kwargs are listed at http://knowledge25.collegenet.com/display/WSW/spaces.xml """ url = "/r25ws/servlet/wrd/run/spaces.xml" if len(kwargs): url += "?%s" % urlencode(kwargs) return s...
python
def _pys2row_heights(self, line): """Updates row_heights in code_array""" # Split with maxsplit 3 split_line = self._split_tidy(line) key = row, tab = self._get_key(*split_line[:2]) height = float(split_line[2]) shape = self.code_array.shape try: if...
java
public void findSourceFiles(Set<String> suffixes, Map<String, Source> foundFiles, Map<String, Module> foundModules, Module currentModule, boolean permitSourcesInDefaultPackage, ...
java
public boolean isValid() { int totalNumberOfColumns = 0; Set<Object> columns = new HashSet<>(); for(Map.Entry<Object, AssociativeArray> entry : internalData.entrySet()) { AssociativeArray row = entry.getValue(); if(columns.isEmpty()) { //this is executed o...
java
public void addDynamicMacro(String name, Factory factory) { if (m_factories == null) { m_factories = new HashMap<String, Factory>(); } m_factories.put(name, factory); }
python
def get_comment_ancestors(comID, depth=None): """ Returns the list of ancestors of the given comment, ordered from oldest to newest ("top-down": direct parent of comID is at last position), up to given depth :param comID: the ID of the comment for which we want to retrieve ancestors :type comID...
python
def show_status(self): """Show status of unregistered migrations""" if not self.check_directory(): return migrations = self.get_unregistered_migrations() if migrations: logger.info('Unregistered migrations:') for migration in migrations: ...
python
def needs_manager_helps(): """Help message for Batch Dialog. .. versionadded:: 3.2.1 :returns: A message object containing helpful information. :rtype: messaging.message.Message """ message = m.Message() message.add(m.Brand()) message.add(heading()) message.add(content()) retu...
python
def _check_suggestions(app_json, publish=False): """ Examines the specified dxapp.json file and warns about any violations of suggestions guidelines. :raises: AppBuilderException for data objects that could not be found """ for input_field in app_json.get('inputSpec', []): for suggestio...
java
public void setOVERCHAR(Integer newOVERCHAR) { Integer oldOVERCHAR = overchar; overchar = newOVERCHAR; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.OVS__OVERCHAR, oldOVERCHAR, overchar)); }
java
public void insertElementAt(Node value, int at) { if (!m_mutable) throw new RuntimeException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_NODESET_NOT_MUTABLE, null)); //"This NodeSet is not mutable!"); if (null == m_map) { m_map = new Node[m_blocksize]; m_mapSize = m_blocksize;...
java
@Override public List<QueueInfo> getQueueInfos() { final List<String> queueNames = getQueueNames(); return PoolUtils.doWorkInPoolNicely(this.jedisPool, new PoolWork<Jedis, List<QueueInfo>>() { /** * {@inheritDoc} */ @Override public List<...
java
public static Expression position(String expression, String substring) { return position(x(expression), substring); }
java
public GetReplicationRunsResult withReplicationRunList(ReplicationRun... replicationRunList) { if (this.replicationRunList == null) { setReplicationRunList(new java.util.ArrayList<ReplicationRun>(replicationRunList.length)); } for (ReplicationRun ele : replicationRunList) { ...
python
def package(env, target, source, PACKAGEROOT, NAME, VERSION, DESCRIPTION, SUMMARY, X_IPK_PRIORITY, X_IPK_SECTION, SOURCE_URL, X_IPK_MAINTAINER, X_IPK_DEPENDS, **kw): """ This function prepares the packageroot directory for packaging with the ipkg builder. """ SCons.Tool.Tool('ipk...
python
def create(vm_): ''' Create a single VM from a data dict ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured( __opts__, __active_provider_name__ or 'dimensiondata', ...
java
public Stream<HString> findAllPatterns(@NonNull Pattern regex) { return Streams.asStream(new Iterator<HString>() { Matcher m = regex.matcher(HString.this); int start = -1; int end = -1; private boolean advance() { if (start == -1) { if (m.find()) { ...
python
def add_value(self, name, value_type, default=None, description=None, value=None): """ Adds a new value to this config header :param name: The name of the value as it would appear in a config file :param value_type: The type of value: bool, str, int, float :param default: The va...
java
static ArchiveInputStream createArchiveInputStream(File archive) throws IOException, ArchiveException { return createArchiveInputStream(new BufferedInputStream(new FileInputStream(archive))); }
java
private PubsubFuture<List<String>> publish0(final List<Message> messages, final String canonicalTopic) { final String path = canonicalTopic + ":publish"; for (final Message message : messages) { if (!isEncoded(message)) { throw new IllegalArgumentException("Message data must be Base64 encoded: " +...