language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def _set_add_(self, v, load=False): """ Setter method for add_, mapped from YANG variable /telemetry/profile/mpls_traffic_fec/add (list) If this variable is read-only (config: false) in the source YANG file, then _set_add_ is considered as a private method. Backends looking to populate this variable...
python
def is_admin(self): """ Check that the user has a role with the code 'admin' """ for ur in self.roleusers: if ur.role.code == 'admin': return True return False
python
def convert_notebook(self, name): """Converts a notebook into a python file.""" #subprocess.call(["jupyter","nbconvert","--to","python", # self.get_path("%s.ipynb"%name)]) exporter = nbconvert.exporters.python.PythonExporter() relative_path = self.convert_path(nam...
python
def activities(self, *args, **kwargs): """Retrieve activities belonging to this scope. See :class:`pykechain.Client.activities` for available parameters. """ if self._client.match_app_version(label='wim', version='<2.0.0', default=True): return self._client.activities(*args,...
python
def get_null_proj(self,nsing=None): """ get a null-space projection matrix of XTQX Parameters ---------- nsing: int optional number of singular components to use If Nonte, then nsing is determined from call to MonteCarlo.get_nsing() R...
java
public List<Specification> getSpecifications(SystemUnderTest sut, Repository repository) { final Criteria crit = sessionService.getSession().createCriteria(Specification.class); crit.createAlias("repository", "repo"); crit.add(Restrictions.eq("repo.uid", repository.getUid())); ...
python
def remove_authentication(self, auth_name=None, organization=None): """ Remove the current authentication or the one given by `auth_name` """ if auth_name: if organization: url = '%s/authentications/org/%s/name/%s' % (self.domain, organization, auth_name) ...
python
async def prompt(self, text=None): ''' Prompt for user input from stdin. ''' if self.sess is None: hist = FileHistory(s_common.getSynPath('cmdr_history')) self.sess = PromptSession(history=hist) if text is None: text = self.cmdprompt ...
python
def update_channels(self): """Update the GUI to reflect channels and image listing. """ if not self.gui_up: return self.logger.debug("channel configuration has changed--updating gui") try: channel = self.fv.get_channel(self.chname) except KeyErro...
java
public HTTPClientConfiguration createHTTPClientConfiguration(ConfigurationHolder configurationHolder) { //get server values String hostName=configurationHolder.getConfigurationValue(HTTPClientConfigurationConstants.HOST_NAME_PROPERTY_KEY); if(hostName==null) { throw new F...
python
def status(self): '''returns rates''' counts = {} for bucket in self.buckets: for x in bucket: if not x in counts: counts[x] = 0 counts[x] += bucket[x] ret = "" mtypes = counts.keys() mtypes.sort() f...
java
public String findParameterAliasByName(String name) { if (parameterName2Alias.containsKey(name)) { return parameterName2Alias.get(name); } return name; }
python
def remove_p(self): """ Like :meth:`remove`, but does not raise an exception if the file does not exist. """ try: self.unlink() except OSError: _, e, _ = sys.exc_info() if e.errno != errno.ENOENT: raise return self
java
public void setHeader(@NonNull View view, boolean padding, boolean divider, DimenHolder height) { mDrawerBuilder.getHeaderAdapter().clear(); if (padding) { mDrawerBuilder.getHeaderAdapter().add(new ContainerDrawerItem().withView(view).withDivider(divider).withHeight(height).withViewPosition(...
python
def parse_from_parent( self, parent, # type: ET.Element state # type: _ProcessorState ): # type: (...) -> Any """Parse the array data from the provided parent XML element.""" item_iter = parent.findall(self._item_path) return self._parse(item_ite...
java
public final ListFindingTypeStatsResponse listFindingTypeStats(ScanRunName parent) { ListFindingTypeStatsRequest request = ListFindingTypeStatsRequest.newBuilder() .setParent(parent == null ? null : parent.toString()) .build(); return listFindingTypeStats(request); }
python
def random(self, shape, tf_fn, kwargs): """Call a random tf operation (e.g. random_uniform). Args: shape: a Shape tf_fn: a function such as tf.random.uniform kwargs: kwargs to pass to tf_fn, except for seed Returns: a LaidOutTensor """ # TODO(noam): can we make things bette...
java
public void put(Object[] subscript, Object value) { put(BrokerUtil.buildSubscript(subscript), value); }
java
public ServiceFuture<StorageAccountInfoInner> getStorageAccountAsync(String resourceGroupName, String accountName, String storageAccountName, final ServiceCallback<StorageAccountInfoInner> serviceCallback) { return ServiceFuture.fromResponse(getStorageAccountWithServiceResponseAsync(resourceGroupName, accountNa...
java
protected void connectAndLogin() throws IOException { if (!ftpClient.isConnected()) { ftpClient.connect(getEndpointConfiguration().getHost(), getEndpointConfiguration().getPort()); if (log.isDebugEnabled()) { log.debug("Connected to FTP server: " + ftpClient.getReplyStri...
java
public double[][] getCovmat() { // Since we worked only on params with dofit=true, we need to expand the // matrix to cover all parameters. double[][] fullcov = new double[numparams][numparams]; for(int i = 0, i2 = 0; i < numparams; i++) { for(int j = 0, j2 = 0; j < numparams; j++) { fullc...
java
private <I extends Message, O extends Message> void invoke( ServerMethod<I, O> method, ByteString payload, long requestId, Channel channel) { FutureCallback<O> callback = new ServerMethodCallback<>(method, requestId, channel); try { I request = method.inputParser().parseFrom(payload); Listenab...
python
def check(self): """ Returns #True if the timeout is exceeded. """ if self.value is None: return False return (time.clock() - self.start) >= self.value
python
def cross(environment, book, row, sheet_source, column_source, column_key): """ Returns a single value from a column from a different dataset, matching by the key. """ a = book.sheets[sheet_source] return environment.copy(a.get(**{column_key: row[column_key]})[column_source])
java
public void resetInterval(Localizable localizable) { final int intervalHorizontalOld = intervalHorizontal; final int intervalVerticalOld = intervalVertical; final double oldX = getX(); final double oldY = getY(); setIntervals(0, 0); offset.setLocation(0.0, 0.0); ...
python
def paw_header(filename, ppdesc): """ Parse the PAW abinit header. Examples: Paw atomic data for element Ni - Generated by AtomPAW (N. Holzwarth) + AtomPAW2Abinit v3.0.5 28.000 18.000 20061204 : zatom,zion,pspdat 7 7 2 0 350 0. : pspcod,...
java
private void updateTextArea(String value) { String oldValue = m_textArea.getValue(); if (!oldValue.equals(value)) { int l1 = oldValue.split("\n").length; int l2 = value.split("\n").length; m_textArea.setValue(value); if (l1 != l2) { schedu...
python
def _checkContactType(self, contactType): """ Possibly emit some warnings about C{contactType}'s implementation of L{IContactType}. @type contactType: L{IContactType} provider """ if getattr(contactType, 'getEditFormForPerson', None) is None: warn( ...
python
def find_consensus(bases): """ find consensus base based on nucleotide frequencies """ nucs = ['A', 'T', 'G', 'C', 'N'] total = sum([bases[nuc] for nuc in nucs if nuc in bases]) # save most common base as consensus (random nuc if there is a tie) try: top = max([bases[nuc] for nuc...
java
@Override public Timer createCalendarTimer(ScheduleExpression schedule, TimerConfig timerConfig) { Serializable info = timerConfig == null ? null : timerConfig.getInfo(); boolean persistent = timerConfig == null || timerConfig.isPersistent(); boolean isTraceOn = TraceComponent.isAnyTrac...
java
private RetriesExhaustedWithDetailsException getExceptions() throws RetriesExhaustedWithDetailsException { if (!hasExceptions.get()) { return null; } ArrayList<MutationException> mutationExceptions = null; synchronized (globalExceptions) { hasExceptions.set(false); if (globalExc...
python
def choose_init(module): """ Select a init system Returns the name of a init system (upstart, sysvinit ...). """ if module.normalized_release.int_major < 7: return 'sysvinit' if not module.conn.remote_module.path_exists("/usr/lib/systemd/system/ceph.target"): return 'sysvinit'...
java
private CmsCreatableListItem makeNavigationLevelItem() { CmsNewResourceInfo typeInfo = getController().getData().getNewNavigationLevelElementInfo(); CmsListItemWidget widget = new CmsListItemWidget(typeInfo); CmsCreatableListItem listItem = new CmsCreatableListItem(widget, typeInfo, NewEntryTyp...
java
@Override public void store(BinaryEntry entry) { try { ByteString key = getRiakKey(entry); ByteString value = ByteString.copyFrom(entry.getBinaryValue().toByteArray()); client.store(new RiakObject(bucket, key, value)); } catch (IOException e) { ...
python
def preferred_jvm_distribution(cls, platforms, strict=False): """Returns a jvm Distribution with a version that should work for all the platforms. Any one of those distributions whose version is >= all requested platforms' versions can be returned unless strict flag is set. :param iterable platforms: ...
java
public static <K, V> HashMap<K, V> toMap(Iterable<Entry<K, V>> entryIter) { return IterUtil.toMap(entryIter); }
java
public void add(long timestamp, Map<String, Object> data) { for (String k : data.keySet()) { if (!columns.contains(k)) { throw new UnknownFieldException(k); } } Map<String, Object> curr = this.rows.get(timestamp); if (curr == null) { t...
python
def xsDateTime_parse(xdt_str, local_tz=None): """ Parses xsDateTime strings of form 2017-01-27T14:58:00+0600, etc. Returns a *naive* datetime in local time according to local_tz. """ if not isinstance(xdt_str, basestring): raise InvalidXSDateTime( "Expecting str or unicode, got {...
java
public long toNanos() { long result = Jdk8Methods.safeMultiply(seconds, NANOS_PER_SECOND); result = Jdk8Methods.safeAdd(result, nanos); return result; }
java
public void recognizeText(String url, TextRecognitionMode mode) { recognizeTextWithServiceResponseAsync(url, mode).toBlocking().single().body(); }
java
protected void activateDestination(DestinationHandler dh) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "activateDestination", dh); if (dh.isLink()) { linkIndex.create(dh); } else { destinationI...
java
private List<String> getDefaultTextValue(FormField field) { // Get the Id String fieldId = field.getName(); // Create new HashMap 'fieldAttributes' and new list 'definedValues' Map<String, String> fieldAttributes = new HashMap<String, String>(); List<String> definedValues = new ArrayList<String>(); //Sto...
python
def _route(self): """Define route.""" # REST API self._app.route('/api/%s/config' % self.API_VERSION, method="GET", callback=self._api_config) self._app.route('/api/%s/config/<item>' % self.API_VERSION, method="GET", callback=self._api_conf...
java
private void unbox(Expression expr, PrimitiveType primitiveType) { TypeElement boxedClass = findBoxedSuperclass(expr.getTypeMirror()); if (primitiveType == null && boxedClass != null) { primitiveType = typeUtil.unboxedType(boxedClass.asType()); } if (primitiveType == null) { return; } ...
java
protected void blockTag() { int p = bp; try { nextChar(); if (isIdentifierStart(ch)) { String name = readTagName(); TagParser tp = tagParsers.get(name); if (tp == null) { blockContent(); } else { ...
python
def _load_pil_image(self, filename): """ Load image using PIL. """ self._channel_data = [] self._original_channel_data = [] im = Image.open(filename) self._image = ImageOps.grayscale(im) im.load() file_data = np.asarray(im, float) file_da...
java
@Override public int read (@Nonnull final byte [] b, @Nonnegative final int nOfs, @Nonnegative final int nLen) throws IOException { ValueEnforcer.isArrayOfsLen (b, nOfs, nLen); final int res = super.read (b, nOfs, nLen); if (res > 0) { m_nCount += res; ...
java
public void free() { if (m_PDatabase != null) m_PDatabase.removePTable(this); m_PDatabase = null; if (m_VKeyList != null) { for (int i = m_VKeyList.size() - 1 ; i >= 0 ;i--) { PKeyArea vKeyArea = (PKeyArea)m_VKeyList.elementAt(i); ...
python
def get_skill_entry(name, skills_data) -> dict: """ Find a skill entry in the skills_data and returns it. """ for e in skills_data.get('skills', []): if e.get('name') == name: return e return {}
python
def stk_description_metadata(description): """Return metadata from MetaMorph image description as list of dict. The MetaMorph image description format is unspecified. Expect failures. """ description = description.strip() if not description: return [] try: description = bytes2s...
python
def determine_hostname(display_name=None): """ Find fqdn if we can """ if display_name: # if display_name is provided, just return the given name return display_name else: socket_gethostname = socket.gethostname() socket_fqdn = socket.getfqdn() try: ...
java
private void accountForIncludedDir(String name, File file, boolean fast) { processIncluded(name, file, dirsIncluded, dirsExcluded, dirsDeselected); if (fast && couldHoldIncluded(name) && !contentsExcluded(name)) { scandir(file, name + File.separator, fast); } }
python
def get_spark_session(enable_hive=False, app_name='marvin-engine', configs=[]): """Return a Spark Session object""" # Prepare spark context to be used import findspark findspark.init() from pyspark.sql import SparkSession # prepare spark sesseion to be returned spark = SparkSession.builder...
python
def get_consumption(self, service_location_id, start, end, aggregation, raw=False): """ Request Elektricity consumption and Solar production for a given service location. Parameters ---------- service_location_id : int start : int | dt.datetime | pd.Timestamp ...
java
static AuthenticationType convertAuthToEnum(int resAuthType) { AuthenticationType authType = AuthenticationType.CONTAINER; if (resAuthType == ResourceRef.AUTH_APPLICATION) { authType = AuthenticationType.APPLICATION; } if (TraceComponent.isAnyTracingEnabled() &&...
java
public static <T> T[] add(final T[] ar, final T e) { final int s = ar.length; final T[] t = Arrays.copyOf(ar, s + 1); t[s] = e; return t; }
python
def calculate_pore_volume(self): """ Return the intrinsic pore volume. Returns ------- :class:`float` The intrinsic pore volume. """ self.pore_volume = sphere_volume(self.calculate_pore_diameter() / 2) self.properties['pore_volume'] = self.po...
java
public void marshall(ResourceConfiguration resourceConfiguration, ProtocolMarshaller protocolMarshaller) { if (resourceConfiguration == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(resourceConfigur...
java
public static CmsXmlContent unmarshal(CmsObject cms, CmsResource resource, ServletRequest req) throws CmsXmlException, CmsLoaderException, CmsException { String rootPath = resource.getRootPath(); if (!CmsResourceTypeXmlContent.isXmlContent(resource)) { // sanity check: resource must be...
java
public void connect(Context context, BeanListener listener) { lastKnownContext = context; beanListener = listener; gattClient.connect(context, device); }
python
def parser(self): """Create the argparser_ for this configuration by adding all settings via the :meth:`Setting.add_argument` method. :rtype: an instance of :class:`ArgumentParser`. """ parser = argparse.ArgumentParser(description=self.description, ...
python
def get_parser(): """Return :py:class:`argparse.ArgumentParser` instance for CLI.""" main_parser = argparse.ArgumentParser( formatter_class=argparse.RawTextHelpFormatter) main_parser.add_argument( '-c', '--config', dest='config', type=str, nargs='?', help='P...
java
@Override @RequestCache public boolean canPrincipalSubscribe( IAuthorizationPrincipal principal, String portletDefinitionId) { String owner = IPermission.PORTAL_SUBSCRIBE; // retrieve the indicated channel from the channel registry store and // determine its current lifecycl...
python
def importaccount(ctx, account, role): """ Import an account using an account password """ from peerplaysbase.account import PasswordKey password = click.prompt("Account Passphrase", hide_input=True) account = Account(account, peerplays_instance=ctx.peerplays) imported = False if role == "...
java
public Map<String, Object> getAllAccumulatorResults() { return accumulatorResults.entrySet() .stream() .collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().getUnchecked())); }
python
def join_url_params(dic): """ 根据传入的键值对,拼接 url 后面 ? 的参数,比如 ?key1=value1&key2=value2 :param: * dic: (dict) 参数键值对 :return: * result: (string) 拼接好的参数 举例如下:: print('--- splice_url_params demo ---') dic1 = {'key1': 'value1', 'key2': 'value2'} print(splice_url_par...
java
@Override public <E> E style(E element, Object data) throws VectorPrintException { if (getValue(DYNAMICDATA, Boolean.class)) { setData(convert(data)); } return element; }
python
def upload_file(self, file): """The method is posting file to the remote server""" url = self._get_url('/api/1.0/upload/post') fcontent = FileContent(file) binary_data = fcontent.get_binary() headers = self._get_request_headers() req = urllib.request.Request(u...
python
def get_alert(self, id, **kwargs): # noqa: E501 """Get a specific alert # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_alert(id, async_req=True) ...
java
public void deregister() { if(objectName == null) { return; } try { MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); if (mbs.isRegistered(objectName)) { mbs.unregisterMBean(objectName); } objectName = null; } catch (Exception e) { throw new RuntimeException(e); ...
java
public void marshall(RegisterDeviceRequest registerDeviceRequest, ProtocolMarshaller protocolMarshaller) { if (registerDeviceRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(registerDeviceRe...
java
private static int med3(int a, int b, int c, IntComparator comp) { int ab = comp.compare(a,b); int ac = comp.compare(a,c); int bc = comp.compare(b,c); return (ab<0 ? (bc<0 ? b : ac<0 ? c : a) : (bc>0 ? b : ac>0 ? c : a)); }
java
@Override public InstallPolicy getInstallPolicy() { if (_asset.getWlpInformation() == null) { return null; } return _asset.getWlpInformation().getInstallPolicy(); }
java
public List<CmsRewriteAlias> getRewriteAliases(CmsObject cms, String siteRoot) throws CmsException { CmsRewriteAliasFilter filter = new CmsRewriteAliasFilter().setSiteRoot(siteRoot); List<CmsRewriteAlias> result = m_securityManager.getRewriteAliases(cms.getRequestContext(), filter); return ...
java
public void init(RemoteTask server, BaseMessageQueue messageQueue) throws RemoteException { super.init(server, messageQueue); m_receiveQueueThread = new Thread(new ReceiveQueueWorker(), "ReceiveQueueWorker"); m_receiveQueueThread.start(); }
python
def deploy(self, args, **extra_args): """Deploy a docker container to a specific container ship (host) :param args: :type args: """ if not isinstance(args, argparse.Namespace): raise TypeError(logger.error("args should of an instance of argparse.Namespace")) ...
java
public static void print(Matrix m, Control control, NumberFormat format) { print(m, control, new NumberFormatNumberFormatter(format)); }
java
public Email bcc(EmailAddress... bcc) { for (EmailAddress b : bcc) { recipient(b, RecipientType.BCC); } return this; }
python
def is_multifile_object_without_children(self, location: str) -> bool: """ Returns True if an item with this location is present as a multifile object without children. For this implementation, this means that there is a file with the appropriate name but without extension :param locati...
java
protected Map getDeviceTokenResponseModel(final OAuth20AccessTokenResponseResult result) { val model = new LinkedHashMap<String, Object>(); val uri = result.getCasProperties().getServer().getPrefix() .concat(OAuth20Constants.BASE_OAUTH20_URL) .concat("/") .concat(OAut...
python
def create_examples_train(candidate_dialog_paths, rng, positive_probability=0.5, max_context_length=20): """ Creates single training example. :param candidate_dialog_paths: :param rng: :param positive_probability: probability of selecting positive training example :return: """ i = 0 ...
java
public static base_responses add(nitro_service client, nssimpleacl6 resources[]) throws Exception { base_responses result = null; if (resources != null && resources.length > 0) { nssimpleacl6 addresources[] = new nssimpleacl6[resources.length]; for (int i=0;i<resources.length;i++){ addresources[i] = new n...
python
def stringify_summary(summary): """ stringify summary, in order to dump json file and generate html report. """ for index, suite_summary in enumerate(summary["details"]): if not suite_summary.get("name"): suite_summary["name"] = "testcase {}".format(index) for record in suite_s...
java
@Override public ListOTAUpdatesResult listOTAUpdates(ListOTAUpdatesRequest request) { request = beforeClientExecution(request); return executeListOTAUpdates(request); }
python
def is_answer_valid(self, ans): """Validate user's answer against available choices.""" return ans in [str(i+1) for i in range(len(self.choices))]
python
def get_api_url(self, lambda_name, stage_name): """ Given a lambda_name and stage_name, return a valid API URL. """ api_id = self.get_api_id(lambda_name) if api_id: return "https://{}.execute-api.{}.amazonaws.com/{}".format(api_id, self.boto_session.region_name, stage...
python
def disable_contact_host_notifications(self, contact): """Disable host notifications for a contact Format of the line that triggers function call:: DISABLE_CONTACT_HOST_NOTIFICATIONS;<contact_name> :param contact: contact to disable :type contact: alignak.objects.contact.Contac...
java
@SuppressWarnings("unchecked") public static <S, I, O> ExtensionResult<S, I, O> empty() { return (ExtensionResult<S, I, O>) EMPTY; }
python
def padded_accuracy(predictions, labels, weights_fn=common_layers.weights_nonzero): """Percentage of times that predictions matches labels on non-0s.""" # If the last dimension is 1 then we're using L1/L2 loss. if common_layers.shape_list(predictions)[-1] == 1: return r...
java
private static Type processTypeForDescendantLookup(Type type) { if (type instanceof ParameterizedType) { return ((ParameterizedType) type).getRawType(); } else { return type; } }
java
public <T> Launch<T> newLaunch(Class<? extends T> programClass) throws LaunchException { return newLaunch(programClass, null); }
python
def get_prep_value(self, value): "Returns field's value prepared for saving into a database." value = self.get_clean_value(value) if self.multiple: if value: value = ",".join(value) else: value = "" return super(CharField, self).get...
python
def iterate_sheets(self, *args, **kwargs): """Opens self.filename and reads it with a csv reader. If self.filename ends with .gz, the file will be decompressed with gzip before being passed to csv.reader. If the filename is not a string, it is assumed to be a file-like object which will be passed direc...
python
def enumerateURL(urlDict, outputFolder, startIndex= 0, maxErrors = 100): """ Function that performs the enumeration itself. """ for i, url in enumerate(urlDict.keys()): # Grabbing domain name: domain = re.findall("://(.*)/", url)[0] # Defining the starting index ...
python
def inserir(self, name): """Inserts a new Division Dc and returns its identifier. :param name: Division Dc name. String with a minimum 2 and maximum of 80 characters :return: Dictionary with the following structure: :: {'division_dc': {'id': < id_division_dc >}} ...
java
public int rank() { if( is64 ) { return SingularOps_DDRM.rank((SingularValueDecomposition_F64)svd, tol); } else { return SingularOps_FDRM.rank((SingularValueDecomposition_F32)svd, (float)tol); } }
python
def eval_table(tbl, expression, vm='python', blen=None, storage=None, create='array', vm_kwargs=None, **kwargs): """Evaluate `expression` against columns of a table.""" # setup storage = _util.get_storage(storage) names, columns = _util.check_table_like(tbl) length = len(columns[0]) ...
python
def closed(self, code, reason=None): """Called when the connection is closed""" self.emit('socket_closed', code, reason) self._recover_network_failure()
java
private static ApplicationLoadResult loadApplication( File projectDirectory, ApplicationTemplateDescriptor appDescriptor, ApplicationLoadResult result ) { ApplicationTemplate app = result.applicationTemplate; result.applicationTemplate.setDirectory( projectDirectory ); // Load the graph File graphDi...
python
def wndifd(a, b): """ Place the difference of two double precision windows into a third window. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wndifd_c.html :param a: Input window A. :type a: spiceypy.utils.support_types.SpiceCell :param b: Input window B. :type b: spiceypy....