language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def register_transform(self, node_class, transform, predicate=None): """Register `transform(node)` function to be applied on the given astroid's `node_class` if `predicate` is None or returns true when called with the node as argument. The transform function may return a value which is ...
java
@BetaApi public final Firewall getFirewall(String firewall) { GetFirewallHttpRequest request = GetFirewallHttpRequest.newBuilder().setFirewall(firewall).build(); return getFirewall(request); }
java
public List<Commit> getCommits(Object projectIdOrPath, int mergeRequestIid, int page, int perPage) throws GitLabApiException { Form formData = new GitLabApiForm().withParam("owned", true).withParam(PAGE_PARAM, page).withParam(PER_PAGE_PARAM, perPage); Response response = get(Response.Status.OK, formDat...
java
public void setAttributes(ArrayList<Attribute> attributes) { if (_attributes != attributes) { _attributes.clear(); _attributes.addAll(attributes); } }
python
def _load_outcome_models(self): """Reloads the outcome models directly from the state""" if not self.state_copy_initialized: return self.outcomes = [] for outcome_m in self.state_copy.outcomes: new_oc_m = deepcopy(outcome_m) new_oc_m.parent = self ...
python
def sigmas_samples(self): r""" Samples of the Gaussian distribution standard deviations """ res = np.empty((self.nsamples, self.nstates, self.dimension), dtype=config.dtype) for i in range(self.nsamples): for j in range(self.nstates): res[i, j, :] = self._sampled_hmms...
python
def process_proxy(self): """ handle PT request :raises ValidateError: if the PGT is not found, or the target service not allowed or the user not allowed on the tardet service. :return: The rendering of ``cas_server/proxy.xml`` :rtype: django.http....
java
private ByteBuffer recv(int attempt) throws IOException, SocketException, SocketTimeoutException { int timeout = UDP_BASE_TIMEOUT_SECONDS * (int) Math.pow(2, attempt); logger.trace("Setting receive timeout to {}s for attempt {}...", timeout, attempt); this.socket.setSoTimeout(timeout *...
python
def extend(base: Dict[Any, Any], extension: Dict[Any, Any]) -> Dict[Any, Any]: '''Extend base by updating with the extension. **Arguments** :``base``: dictionary to have keys updated or added :``extension``: dictionary to update base with **Return Value(s)** Resulting dictionary from up...
java
static String getMethodSpecificName(Method m) { return m == null ? null : m.getDeclaringClass().getName() + '.' + getSignature(m); }
java
public Observable<VirtualMachineExtensionInner> getAsync(String resourceGroupName, String vmName, String vmExtensionName) { return getWithServiceResponseAsync(resourceGroupName, vmName, vmExtensionName).map(new Func1<ServiceResponse<VirtualMachineExtensionInner>, VirtualMachineExtensionInner>() { @O...
python
def _init_client(): '''Setup client and init datastore. ''' global client, path_prefix if client is not None: return etcd_kwargs = { 'host': __opts__.get('etcd.host', '127.0.0.1'), 'port': __opts__.get('etcd.port', 2379), 'protocol': __opts__.get('etcd.pr...
java
public static Func0<Observable<Void>> toAsync(Action0 action) { return toAsync(action, Schedulers.computation()); }
java
@Override public R visitDocRoot(DocRootTree node, P p) { return defaultAction(node, p); }
java
public OvhPrivateLinkRequest serviceName_privateLink_peerServiceName_request_GET(String serviceName, String peerServiceName) throws IOException { String qPath = "/router/{serviceName}/privateLink/{peerServiceName}/request"; StringBuilder sb = path(qPath, serviceName, peerServiceName); String resp = exec(qPath, "G...
python
def verb_chain_starts(self): """The start positions of ``verb_chains`` elements.""" if not self.is_tagged(VERB_CHAINS): self.tag_verb_chains() return self.starts(VERB_CHAINS)
java
public TTTTransition<I, D> getInternalTransition(TTTState<I, D> state, I input) { int inputIdx = alphabet.getSymbolIndex(input); return getInternalTransition(state, inputIdx); }
python
def _findCRefPattern(self, xml): """ Find CRefPattern in the text and set object.citation :param xml: Xml Resource :type xml: lxml.etree._Element :return: None """ if not self.citation.is_set(): citation = xml.xpath("//tei:refsDecl[@n='CTS']", namespaces=XPATH...
python
def serialize_to_dict(dictionary): '''Make a json-serializable dictionary from input dictionary by converting non-serializable data types such as numpy arrays.''' retval = {} for k, v in dictionary.items(): if isinstance(v, dict): retval[k] = serialize_to_dict(v) else: ...
python
def specimens_extract(spec_file='specimens.txt', output_file='specimens.xls', landscape=False, longtable=False, output_dir_path='.', input_dir_path='', latex=False): """ Extracts specimen results from a MagIC 3.0 format specimens.txt file. Default output format is an Excel file. t...
java
public void setForegroundColor(final Color COLOR) { if (null == foregroundColor) { _foregroundColor = COLOR; fireTileEvent(REDRAW_EVENT); } else { foregroundColor.set(COLOR); } }
python
def run_jnb(input_path, output_path=r"///_run_jnb/*-output", execution_path=r'///input', return_mode='except', overwrite=False, timeout=ExecutePreprocessor.timeout.default_value, kernel_name=ExecutePreprocessor.kernel_name.default_value, ep_kwargs=...
python
def profile_validation(self, status): """Return run total value.""" self.selected_profile.data.setdefault('validation_pass_count', 0) self.selected_profile.data.setdefault('validation_fail_count', 0) if status: self.selected_profile.data['validation_pass_count'] += 1 ...
java
@SuppressWarnings("unchecked") public <E> TerminalResult IN_list(E... value) { getPredicateExpression().setOperator(Operator.IN); getPredicateExpression().setValue_2(value); TerminalResult ret = APIAccess.createTerminalResult(this.getPredicateExpression()); QueryRecorder.recordInvocation(this, "IN_list", ret, ...
java
@RequirePOST public HttpResponse doApproveAll() throws IOException { StringBuilder buf = new StringBuilder(); for (Class c : rejected.get()) { buf.append(c.getName()).append('\n'); } whitelisted.append(buf.toString()); return HttpResponses.ok(); }
java
@Override public void setHTML(final String html) { super.setHTML(html); DomEvent.fireNativeEvent(Document.get().createChangeEvent(), this); }
java
@Override public Reader getResource(JoinableResourceBundle bundle, String resourceName, boolean processingBundle) { Reader rd = null; String realPath = getRealResourcePath(resourceName); if (isFileSystemPath(resourceName, realPath)) { // The resource has been // remapped try { rd = new File...
java
private void designRectangularPipe( double tau, double g, double maxd, double c, StringBuilder strWarnings ) { /* [cm] base della sezione effettivamente adottata. */ double base; /* * [%] pendenza naturale, calcolata in funzione dei dati geometrici * della rete */ ...
python
def get_rendered_toctree(builder, docname, prune=False, collapse=True): """Build the toctree relative to the named document, with the given parameters, and then return the rendered HTML fragment. """ fulltoc = build_full_toctree(builder, docname, ...
java
public void sendCmsRedirect(String location) throws IOException { // TOOD: IBM Websphere v5 has problems here, use forward instead (which has other problems) getJsp().getResponse().sendRedirect(OpenCms.getSystemInfo().getOpenCmsContext() + location); }
python
def init(config): """ Initialise ~./sedge/config file if none exists. Good for first time sedge usage """ from pkg_resources import resource_stream import shutil config_file = Path(config.config_file) if config_file.is_file(): click.echo('{} already exists, maybe you want $ sedg...
python
def check_bidi(chars): """ Check proper bidirectionality as per stringprep. Operates on a list of unicode characters provided in `chars`. """ # the empty string is valid, as it cannot violate the RandALCat constraints if not chars: return # first_is_RorAL = unicodedata.bidirectiona...
python
def _calculate_eta(self, progress, data, value, elapsed): '''Updates the widget to show the ETA or total time when finished.''' if elapsed: # The max() prevents zero division errors per_item = elapsed.total_seconds() / max(value, 1e-6) remaining = progress.max_value -...
java
public void compress3( AutoBuffer ab ) { assert max() > 32; // Expect a larger format assert _byteoff == 0; // This is only set on loading a pre-existing IcedBitSet assert _val.length==numBytes(); ab.put2((char)_bitoff); ab.put4(_nbits); ab.putA1(_val,_val.length); }
python
def read_base_distrib_data(line_iter): """ Consumes lines from the provided line_iter and parses those lines for base distribution data. Data should be tab separated and immediately preceded by a line of headers: READ_END CYCLE PCT_A PCT_C PCT_G PCT_T PCT_N Returns either None or a dict...
java
public static X509Name getInstance( ASN1TaggedObject obj, boolean explicit) { return getInstance(ASN1Sequence.getInstance(obj, explicit)); }
python
def is_sequence(value): """Determine if a value is a sequence type. Returns: ``True`` if `value` is a sequence type (e.g., ``list``, or ``tuple``). String types will return ``False``. NOTE: On Python 3, strings have the __iter__ defined, so a simple hasattr check is insufficient. """ ...
java
public static IndexSummary downsample(IndexSummary existing, int newSamplingLevel, int minIndexInterval, IPartitioner partitioner) { // To downsample the old index summary, we'll go through (potentially) several rounds of downsampling. // Conceptually, each round starts at position X and then remove...
python
def _determine_tool(files): """Yields tuples in the form of (linker file, tool the file links for""" for file in files: linker_ext = file.split('.')[-1] if "sct" in linker_ext or "lin" in linker_ext: yield (str(file),"uvision") elif "ld" in linker_ext: yield (str(...
python
def log_call(call_name): """Log the API call to the logger.""" def decorator(f): @wraps(f) def wrapper(*args, **kw): instance = args[0] instance.logger.info(call_name, {"content": request.get_json()}) return f(*args, **kw) return wrapper return dec...
java
public void executeSystemTask(WorkflowSystemTask systemTask, String taskId, int unackTimeout) { try { Task task = executionDAOFacade.getTaskById(taskId); if (task == null) { LOGGER.error("TaskId: {} could not be found while executing SystemTask", taskId); ...
python
def import_from_pypower_ppc(network, ppc, overwrite_zero_s_nom=None): """ Import network from PYPOWER PPC dictionary format version 2. Converts all baseMVA to base power of 1 MVA. For the meaning of the pypower indices, see also pypower/idx_*. Parameters ---------- ppc : PYPOWER PPC dict ...
java
@Override public void clearRecord(String crawlerName) { try { RBloomFilter<String> bloomFilter = getFilter(crawlerName); bloomFilter.delete(); } catch (Exception e) { logger.warn(e.getMessage()); } }
python
def get_policy_configurations(self, project, repository_id=None, ref_name=None, policy_type=None, top=None, continuation_token=None): """GetPolicyConfigurations. [Preview API] Retrieve a list of policy configurations by a given set of scope/filtering criteria. :param str project: Project ID or p...
java
public static String adjustHtmlEncoding(String input, String encoding) { return encodeHtmlEntities(decodeHtmlEntities(input, encoding), encoding); }
java
public TableLayoutBuilder cell(JComponent component, String attributes) { Cell cc = cellInternal(component, attributes); lastCC = cc; items.add(cc); return this; }
python
def home(self): """ Home the pipette's plunger axis during a protocol run Notes ----- `Pipette.home()` homes the `Robot` Returns ------- This instance of :class:`Pipette`. Examples -------- .. >>> from opentrons import i...
java
public static Option[] editConfigurationFilePut(final String configurationFilePath, File source, String... keysToUseFromSource) { return createOptionListFromFile(source, new FileOptionFactory() { @Override public Option createOption(String key, Object value) { re...
python
def get_os(): """ Human-friendly OS name """ if sys.platform == 'darwin': return 'mac' elif sys.platform.find('freebsd') != -1: return 'freebsd' elif sys.platform.find('linux') != -1: return 'linux' elif sys.platform.find('win32') != -1: return 'windows' e...
java
private boolean updateChargingStationOpeningTimes(ChargingStationOpeningTimesChangedEvent event, boolean clear) { ChargingStation chargingStation = repository.findOne(event.getChargingStationId().getId()); if (chargingStation != null) { if (!event.getOpeningTimes().isEmpty()) { ...
python
def iterate(self, n=None, n_upto=None, t=None, t_upto=None, output_every=None, t_output_every=None): """Run the model for a number of iterations, expressed in a number of options. Only one iteration argument should be passed. Only one output arguments shou...
python
def SearchSeasonDirTable(self, showID, seasonNum): """ Search SeasonDir table. Find the season directory for a given show id and season combination. Parameters ---------- showID : int Show id for given show. seasonNum : int Season number. Returns ---------- ...
java
public static File getClasspathFile(String filename) { if(filename == null) { throw LOG.nullParameter("filename"); } return getClasspathFile(filename, null); }
java
public void initializeMultipleModules( IExecutionEnvironment execEnv, List<? extends IModule> modules ) { ((ExecutionEnvironment)execEnv).initializeMultipleModules( modules ); }
java
private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } FileInputStream input = new FileInputStream(srcFile); FileOutputS...
python
def ripple_withdrawal(self, amount, address, currency): """ Returns true if successful. """ data = {'amount': amount, 'address': address, 'currency': currency} response = self._post("ripple_withdrawal/", data=data, return_json=True) return se...
java
public LocalDate withMonth(int month) { if (this.month == month) { return this; } MONTH_OF_YEAR.checkValidValue(month); return resolvePreviousValid(year, month, day); }
java
private Single<String> getIdColName(String tableName) { String alias = "idColumnName"; return new CustomSelectAction() { @Override protected String patternSql() { return String.format("SELECT k.COLUMN_NAME as %s\n" + "FROM information_schem...
python
def load_libdmtx(): """Loads the libdmtx shared library. Populates the globals LIBDMTX and EXTERNAL_DEPENDENCIES. """ global LIBDMTX global EXTERNAL_DEPENDENCIES if not LIBDMTX: LIBDMTX = dmtx_library.load() EXTERNAL_DEPENDENCIES = [LIBDMTX] return LIBDMTX
java
public static String getLabel(ComponentJob job, boolean includeDescriptorName, boolean includeInputColumnNames, boolean includeRequirements) { final String jobName = job.getName(); final StringBuilder label = new StringBuilder(); if (Strings.isNullOrEmpty(jobName)) { if (...
java
public Map<String, String> getFlattened() { final TreeMap<String, String> returnVal = new TreeMap<>(); returnVal.putAll(getMapByPrefix("")); return returnVal; }
python
def load_project(self, path): """ Load a Tarbell project """ base = self._get_base(path) filename, pathname, description = imp.find_module('tarbell_config', [path]) project = imp.load_module('project', filename, pathname, description) try: self.key =...
python
def dim_global_size_dict(self): """ Returns a mapping of dimension name to global size """ return { d.name: d.global_size for d in self._dims.itervalues()}
python
def stable_specie(): ''' provide the list of stable species, and decay path feeding stables ''' #import numpy as np stable_raw=[] stable_raw = ['H 1', 'H 2',\ 'HE 3', 'HE 4',\ 'LI 6', 'LI 7',\ 'BE 9',\ 'B 10', 'B 11',\ 'C 12', 'C 13',\ 'N 14', 'N 15',\ 'O ...
java
private <Delegated> MvpPresenter<? super Delegated> getMvpPresenter(Delegated target, PresenterField<Delegated> presenterField, String delegateTag) { Class<? extends MvpPresenter<?>> presenterClass = presenterField.getPresenterClass(); PresenterStore presenterStore = MvpFacade.getInstance().getPresenterStore(); ...
java
@Route(method= HttpMethod.POST, uri="/") public Result post(@FormParameter("id") String id, @FormParameter("name") String name) { // The values of id and names are computed the request attributes. return ok(id + " - " + name); }
java
private ImmutableMap<Integer, Integer> lightEREOffsetToEDTOffset(String document) { final ImmutableMap.Builder<Integer, Integer> offsetMap = ImmutableMap.builder(); int EDT = 0; // lightERE treats these as one, not two (as an XML parser would) document = document.replaceAll("\\r\\n", "\n"); for (int...
java
private static Iterator<String> getPidIterator(ValidatorProcessParameters parms, RemoteObjectSource objectSource) throws ObjectSourceException { if (parms.getIteratorType() == IteratorType.FS_QUERY) { return objectSource.findObjectPids(p...
python
def metadata_to_dict(metadata): """ Looks at metadata.xml file of sentinel product and extract useful keys Returns a python dict """ tree = etree.parse(metadata) root = tree.getroot() meta = OrderedDict() keys = [ 'SPACECRAFT_NAME', 'PRODUCT_STOP_TIME', 'Cloud_Coverage...
python
def _set_fcoe_fip_keep_alive(self, v, load=False): """ Setter method for fcoe_fip_keep_alive, mapped from YANG variable /fcoe/fcoe_fabric_map/fcoe_fip_keep_alive (container) If this variable is read-only (config: false) in the source YANG file, then _set_fcoe_fip_keep_alive is considered as a private ...
java
public void shutdownAndWait() { try { client.shutdown().get(); LOG.info("The Queryable State Client was shutdown successfully."); } catch (Exception e) { LOG.warn("The Queryable State Client shutdown failed: ", e); } }
python
def time_before_caveat(t): '''Return a caveat that specifies that the time that it is checked at should be before t. :param t is a a UTC date in - use datetime.utcnow, not datetime.now ''' return _first_party(COND_TIME_BEFORE, pyrfc3339.generate(t, accept_naive=True, ...
python
def change_existence(self, is_hidden): # type: (bool) -> None ''' Change the ISO9660 existence flag of this Directory Record. Parameters: is_hidden - True if this Directory Record should be hidden, False otherwise. Returns: Nothing. ''' if not s...
python
def as_datetime(self): '''Get as python datetime.datetime. Require year to be a valid datetime year. Default month and day to 1 if do not exist. @return: datetime.datetime object. ''' year = int(self.year) month = int(self.month) if self.month else 1 day...
python
def get_gene(self) -> Gene: """Get the corresponding gene or raise an exception if it's not the reference node. :raises: InferCentralDogmaException """ if self.variants: raise InferCentralDogmaException('can not get gene for variant') return Gene( namesp...
java
public void close() throws IOException, InterruptedException { for (int i = 0; i < this.getNumberOfInputChannels(); i++) { final InputChannel<T> inputChannel = this.channels[i]; inputChannel.close(); } }
java
public void marshall(ApproveSkillRequest approveSkillRequest, ProtocolMarshaller protocolMarshaller) { if (approveSkillRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(approveSkillRequest.ge...
java
public static Function<Object,Character> methodForCharacter(final String methodName, final Object... optionalParameters) { return new Call<Object,Character>(Types.CHARACTER, methodName, VarArgsUtil.asOptionalObjectArray(Object.class,optionalParameters)); }
java
public Signature dropLast(int n) { return new Signature( methodType.dropParameterTypes(methodType.parameterCount() - n, methodType.parameterCount()), Arrays.copyOfRange(argNames, 0, argNames.length - n)); }
java
@Override public @Nonnull ApplicationContextBuilder exclude(@Nullable String... configurations) { if (configurations != null) { this.configurationExcludes.addAll(Arrays.asList(configurations)); } return this; }
python
def process_star(filename, output, *, extension, star_name, period, shift, parameters, period_label, shift_label, **kwargs): """Processes a star's lightcurve, prints its coefficients, and saves its plotted lightcurve to a file. Returns the result of get_lightcurve. """ if star_name is N...
java
public static com.liferay.commerce.discount.model.CommerceDiscountUsageEntry createCommerceDiscountUsageEntry( long commerceDiscountUsageEntryId) { return getService() .createCommerceDiscountUsageEntry(commerceDiscountUsageEntryId); }
java
public static Set<Method> getOverrideHierarchy(final Method method, final Interfaces interfacesBehavior) { Validate.notNull(method); final Set<Method> result = new LinkedHashSet<>(); result.add(method); final Class<?>[] parameterTypes = method.getParameterTypes(); final Class<?...
python
def filter_repos(config, repo_dir=None, vcs_url=None, name=None): """Return a :py:obj:`list` list of repos from (expanded) config file. repo_dir, vcs_url and name all support fnmatch. :param config: the expanded repo config in :py:class:`dict` format. :type config: dict :param repo_dir: directory ...
python
def _set_private_vlan_trunk(self, v, load=False): """ Setter method for private_vlan_trunk, mapped from YANG variable /interface/port_channel/switchport/mode/private_vlan/private_vlan_trunk (container) If this variable is read-only (config: false) in the source YANG file, then _set_private_vlan_trunk is...
java
@Override public NamingRegisterRequest decode(final byte[] buf) { final AvroNamingRegisterRequest avroNamingRegisterRequest = AvroUtils.fromBytes(buf, AvroNamingRegisterRequest.class); return new NamingRegisterRequest( new NameAssignmentTuple(factory.getNewInstance(avroNamingRegisterRequest.ge...
java
public RequestChannel getRequestChannel(Object client) { try { InvocationHandler genericHandler = Proxy.getInvocationHandler(client); ThriftInvocationHandler thriftHandler = (ThriftInvocationHandler) genericHandler; return thriftHandler.getChannel(); } cat...
python
def put_many(self, items: Iterable[T], context: PipelineContext = None) -> None: """Puts multiple objects of the same type into the data sink. The objects may be transformed into a new type for insertion if necessary. Args: items: An iterable (e.g. list) of objects to be inserted into the d...
python
def assertion(func): """Extend sure with a custom assertion method.""" func = assertionmethod(func) setattr(AssertionBuilder, func.__name__, func) return func
python
def _prepare_output(partitions, verbose): """Returns dict with 'raw' and 'message' keys filled.""" out = {} partitions_count = len(partitions) out['raw'] = { 'offline_count': partitions_count, } if partitions_count == 0: out['message'] = 'No offline partitions.' else: ...
java
public Observable<Page<ExpressRouteCircuitInner>> listNextAsync(final String nextPageLink) { return listNextWithServiceResponseAsync(nextPageLink) .map(new Func1<ServiceResponse<Page<ExpressRouteCircuitInner>>, Page<ExpressRouteCircuitInner>>() { @Override public Page...
java
public void configure(String configuration) throws IOException { URL url=Resource.newResource(configuration).getURL(); if (_configuration!=null && _configuration.equals(url.toString())) return; if (_configuration!=null) throw new IllegalStateException("Alread...
python
def scan_results(self, obj): """Get the AP list after scanning.""" bsses = [] bsses_summary = self._send_cmd_to_wpas(obj['name'], 'SCAN_RESULTS', True) bsses_summary = bsses_summary[:-1].split('\n') if len(bsses_summary) == 1: return bsses for l in bsses_sum...
java
static void registerDefaultValues(String annotation, Map<String, Object> defaultValues) { if (StringUtils.isNotEmpty(annotation)) { ANNOTATION_DEFAULTS.put(annotation.intern(), defaultValues); } }
python
def _teardown(self): "Handles the restoration of any potential global state set." self.example.after(self.context) if self.is_root_runner: run.after_all.execute(self.context) #self.context = self.context._parent self.has_ran = True
java
private Object getMethods(Class sender, String name, boolean isCallToSuper) { Object answer; final MetaMethodIndex.Entry entry = metaMethodIndex.getMethods(sender, name); if (entry == null) answer = FastArray.EMPTY_LIST; else if (isCallToSuper) { ...
python
def checkerboard_matrix_filtering(similarity_matrix, kernel_width, peak_range): """ Moving the checkerboard matrix over the main diagonal of the similarity matrix one sample at a time. :param similarity_matrix: :param peak_range: the number of samples in which the peak detection algorithms finds a peak...
python
def find_iteration( url: Union[methods, str], itermode: Optional[str] = None, iterkey: Optional[str] = None, ) -> Tuple[str, str]: """ Find iteration mode and iteration key for a given :class:`slack.methods` Args: url: :class:`slack.methods` or string url itermode: Custom iterat...
java
public void marshall(WorkGroupConfiguration workGroupConfiguration, ProtocolMarshaller protocolMarshaller) { if (workGroupConfiguration == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(workGroupConf...
python
def _fill_column_holes(self): ''' Same as _fill_row_holes but for columns. ''' for column_index in range(self.start[1], self.end[1]): table_column = TableTranspose(self.table)[column_index] column_start = table_column[self.start[0]] if is_text_cell(col...