language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public boolean containsKey(Object key) { purge(); Entry entry = getEntry(key); if (entry == null) return false; return entry.getValue() != null; }
python
def _fft_convolve_gpu(data_g, h_g, res_g = None, plan = None, inplace = False, kernel_is_fft = False): """ fft convolve for gpu buffer """ assert_bufs_type(np.complex64,data_g,h_g) if data_g.shape != h_g.shape: raise ValueError("data and kernel mu...
java
public void marshall(GetAuthorizerRequest getAuthorizerRequest, ProtocolMarshaller protocolMarshaller) { if (getAuthorizerRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(getAuthorizerReques...
java
public ZealotKhala orNotLikePattern(String field, String pattern) { return this.doLikePattern(ZealotConst.OR_PREFIX, field, pattern, true, false); }
java
synchronized PageWrapper getRootPage() { return this.pageByOffset.values().stream() .filter(page -> page.getParent() == null) .findFirst().orElse(null); }
java
@Override public RoundedMoney divide(Number divisor) { BigDecimal bd = MoneyUtils.getBigDecimal(divisor); if (isOne(bd)) { return this; } RoundingMode rm = monetaryContext.get(RoundingMode.class); if(rm==null){ rm = RoundingMode.HALF_EVEN; } ...
python
def refresh_db(full=False, **kwargs): ''' Updates the remote repos database. full : False Set to ``True`` to force a refresh of the pkg DB from all publishers, regardless of the last refresh time. CLI Example: .. code-block:: bash salt '*' pkg.refresh_db salt '*'...
python
def transfer_user(self, username, transfer_address, owner_privkey): """ Transfer name on blockchain """ url = self.base_url + "/users/" + username + "/update" owner_pubkey = get_pubkey_from_privkey(owner_privkey) payload = { 'transfer_address': transfer...
java
public static void elementMult( DMatrix2 a , DMatrix2 b , DMatrix2 c ) { c.a1 = a.a1*b.a1; c.a2 = a.a2*b.a2; }
python
def disconnect(self): """Disconnect from event stream.""" _LOGGING.debug('Disconnecting from stream: %s', self.name) self.kill_thrd.set() self.thrd.join() _LOGGING.debug('Event stream thread for %s is stopped', self.name) self.kill_thrd.clear()
python
def save(self, output: Union[str, BinaryIO], series: Optional[str] = None, deps: Iterable=tuple(), create_missing_dirs: bool=True) -> "Model": """ Serialize the model to a file. :param output: Path to the file or a file object. :param series: Name of the model series. If it...
java
public static String javaStringEscape(@NonNull String string) { StringBuilder b = new StringBuilder(); for (char c : string.toCharArray()) { if (c >= 128) { b.append("\\u").append(String.format("%04X", (int) c)); } else { b.append(c); } } return...
java
private boolean isExistCmisObject(String path) { try { session.getObjectByPath(path); return true; } catch (CmisObjectNotFoundException e) { return false; } }
java
private String getDataType(String[] items) { for (String item : items) { if (XsdDatatypeEnum.ENTITIES.isDataType(item)) { return item; } } return items[0]; }
python
def _closing_bracket_index(self, text, bpair=('(', ')')): """Return the index of the closing bracket that matches the opening bracket at the start of the text.""" level = 1 for i, char in enumerate(text[1:]): if char == bpair[0]: level += 1 elif char == bp...
java
private Object decodeResult(IoBuffer data) { log.debug("decodeResult - data limit: {}", (data != null ? data.limit() : 0)); processHeaders(data); Input input = new Input(data); String target = null; byte b = data.get(); //look for SOH if (b == 0) { ...
java
private ConversionMethod verifyConversionExistence(List<ConversionMethod> conversions){ for (ConversionMethod method : conversions) if(isPresentIn(method.getFrom(),sourceName) && isPresentIn(method.getTo() ,destinationName)) return method; return null; }
python
def dephasing_operators(p): """ Return the phase damping Kraus operators """ k0 = np.eye(2) * np.sqrt(1 - p / 2) k1 = np.sqrt(p / 2) * Z return k0, k1
python
def GenerateCalendarDatesFieldValuesTuples(self): """Generates tuples of calendar_dates.txt values. Yield zero tuples if this ServicePeriod should not be in calendar_dates.txt .""" for date, (exception_type, _) in self.date_exceptions.items(): yield (self.service_id, date, unicode(exception_type))
java
public void marshall(EntityFilter entityFilter, ProtocolMarshaller protocolMarshaller) { if (entityFilter == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(entityFilter.getEventArns(), EVENTARNS_BIND...
python
def editor(self, value): """ Setter for **self.__editor** attribute. :param value: Attribute value. :type value: Editor """ if value is not None: assert type(value) is Editor, "'{0}' attribute: '{1}' type is not 'Editor'!".format("editor", value) sel...
python
def salm2map(salm, s, lmax, Ntheta, Nphi): """Convert mode weights of spin-weighted function to values on a grid Parameters ---------- salm : array_like, complex, shape (..., (lmax+1)**2) Input array representing mode weights of the spin-weighted function. This array may be multi-dimen...
python
def _get_attribute(self, attribute, name): """Device attribute getter""" try: if attribute is None: attribute = self._attribute_file_open( name ) else: attribute.seek(0) return attribute, attribute.read().strip().decode() except...
python
def run_slurm(self, steps=None, **kwargs): """Run the steps via the SLURM queue.""" # Optional extra SLURM parameters # params = self.extra_slurm_params params.update(kwargs) # Mandatory extra SLURM parameters # if 'time' not in params: params['time'] = self.d...
python
def _query(self, ResponseGroup="Large", **kwargs): """Query. Query Amazon search and check for errors. :return: An lxml root element. """ response = self.api.ItemSearch(ResponseGroup=ResponseGroup, **kwargs) root = objectify.fromstring(response) if (...
java
public PolicyExecutor create(String fullIdentifier, String owner) { return new PolicyExecutorImpl((ExecutorServiceImpl) globalExecutor, fullIdentifier, owner, policyExecutors); }
python
def read_mm_uic2(fd, byte_order, dtype, count): """Read MM_UIC2 tag from file and return as dictionary.""" result = {'number_planes': count} values = numpy.fromfile(fd, byte_order+'I', 6*count) result['z_distance'] = values[0::6] // values[1::6] #result['date_created'] = tuple(values[2::6]) #res...
java
@Nonnull public CSSURI setURI (@Nonnull final String sURI) { ValueEnforcer.notNull (sURI, "URI"); if (CSSURLHelper.isURLValue (sURI)) throw new IllegalArgumentException ("Only the URI and not the CSS-URI value must be passed!"); m_sURI = sURI; return this; }
python
def empirical_retinotopy_data(hemi, retino_type): ''' empirical_retinotopy_data(hemi, t) yields a numpy array of data for the given cortex object hemi and retinotopy type t; it does this by looking at the properties in hemi and picking out any combination that is commonly used to denote empirical retino...
python
def render_syntax_error( project: 'projects.Project', error: SyntaxError ) -> dict: """ Renders a SyntaxError, which has a shallow, custom stack trace derived from the data included in the error, instead of the standard stack trace pulled from the exception frames. :param project: ...
java
public Observable<Page<MediaServiceInner>> listByResourceGroupAsync(String resourceGroupName) { return listByResourceGroupWithServiceResponseAsync(resourceGroupName).map(new Func1<ServiceResponse<List<MediaServiceInner>>, Page<MediaServiceInner>>() { @Override public Page<MediaServiceInn...
python
def os_version_info_ex(): ''' Helper function to return the results of the GetVersionExW Windows API call. It is a ctypes Structure that contains Windows OS Version information. Returns: class: An instance of a class containing version info ''' if not HAS_WIN32: return clas...
python
def contains_raw(self, etag): """When passed a quoted tag it will check if this tag is part of the set. If the tag is weak it is checked against weak and strong tags, otherwise strong only.""" etag, weak = unquote_etag(etag) if weak: return self.contains_weak(etag) ...
python
def query(self, domain): """The actual query happens here. Time from queries is replaced with isoformat. :param domain: The domain which should gets queried. :type domain: str :returns: List of dicts containing the search results. :rtype: [list, dict] """ result ...
java
public static String stringToString(String src, String srcfmt, String desfmt) { return dateToString(stringToDate(src, srcfmt), desfmt); }
python
def _printStats(self, graph, hrlinetop=False): """ shotcut to pull out useful info for interactive use 2016-05-11: note this is a local version of graph.printStats() """ if hrlinetop: self._print("----------------", "TIP") self._print("Ontologies......: %d" % len(grap...
java
public synchronized Servlet getServlet() throws ServletException { // Handle previous unavailability if (_unavailable!=0) { if (_unavailable<0 || _unavailable>0 && System.currentTimeMillis()<_unavailable) throw _unavailableEx; _unavailable=0; ...
java
static void linearTimeIncrementHistogramCounters(final DoublesBufferAccessor samples, final long weight, final double[] splitPoints, final double[] counters) { int i = 0; int j = 0; while (i < samples.numItems() && j < splitPoints.length) { if (samples.get(i) < splitPoints[j]) { counters...
python
def plot_data_filter(data, data_f, b, a, cutoff, fs): '''Plot frequency response and filter overlay for butter filtered data Args ---- data: ndarray Signal array data_f: float Signal sampling rate b: array_like Numerator of a linear filter a: array_like Denom...
python
def get_archive_types(): ''' Return information related to the types of archives available ''' ret = copy.deepcopy(_bundle_types) for k, v in ret.items(): v.pop('handler') return ret
java
public EntityType getEntityType(Class<?> clazz) { EntityType type = context.getEntityType(clazz); if (null == type) { type = new EntityType(clazz); } return type; }
python
def _energy_distance_imp(x, y, exponent=1): """ Real implementation of :func:`energy_distance`. This function is used to make parameter ``exponent`` keyword-only in Python 2. """ x = _transform_to_2d(x) y = _transform_to_2d(y) _check_valid_energy_exponent(exponent) distance_xx = ...
java
private void resetAnimation(){ mLastUpdateTime = SystemClock.uptimeMillis(); mLastProgressStateTime = mLastUpdateTime; if(mProgressMode == ProgressView.MODE_INDETERMINATE){ mStartLine = mReverse ? getBounds().width() : 0; mStrokeColorIndex = 0; mLineWidth = mReverse ? -mMinLineWidth : mMinLineWidth; ...
java
public static Intent openPlayStore(Context context, boolean openInBrowser) { String appPackageName = context.getPackageName(); Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)); if (isIntentAvailable(context, marketIntent)) { ret...
python
def labeled_accumulate(sequence, keygetter=operator.itemgetter(0), valuegetter=operator.itemgetter(1), accumulator=operator.add): """ Accumulates input elements according to accumulate(), but keeping certain data (per element, from the original sequence/iterable) in the target elements, like behaving as k...
java
public void close() { synchronized (this) { if (this.closed) { return; } this.closed = true; } this.numRecordsInBuffer = 0; this.numRecordsReturned = 0; // add the full segments to the empty ones for (int i = this.fullSegments.size() - 1; i >= 0; i--) { this.emptySegments.add(this.full...
python
def _unapply_xheaders(self) -> None: """Undo changes from `_apply_xheaders`. Xheaders are per-request so they should not leak to the next request on the same connection. """ self.remote_ip = self._orig_remote_ip self.protocol = self._orig_protocol
java
@Override public boolean setActive() { WebLocator inactiveTab = getTitleInactiveEl().setExcludeClasses("x-tab-active"); boolean activated = isActive() || inactiveTab.click(); if (activated) { log.info("setActive : " + toString()); } return activated; }
python
def solve(self, scenario, solver): """ Decompose each cluster into separate units and try to optimize them separately :param scenario: :param solver: Solver that may be used to optimize partial networks """ clusters = set(self.clustering.busmap.values) n =...
python
def _getFromTime(self, atDate=None): """ Time that the event starts (in the local time zone). """ return getLocalTime(self.date, self.time_from, self.tz)
java
public PagedList<SecretItem> getSecretVersions(final String vaultBaseUrl, final String secretName, final Integer maxresults) { ServiceResponse<Page<SecretItem>> response = getSecretVersionsSinglePageAsync(vaultBaseUrl, secretName, maxresults).toBlocking().single(); return new PagedList<SecretItem>(respo...
python
def short_codes(self): """ Access the short_codes :returns: twilio.rest.proxy.v1.service.short_code.ShortCodeList :rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeList """ if self._short_codes is None: self._short_codes = ShortCodeList(self._version, ...
java
private void populateRequestHeaders(HttpURLConnection httpUrlConnection, Map<String, String> requestHeaders) { Set<String> keySet = requestHeaders.keySet(); Iterator<String> keySetIterator = keySet.iterator(); while (keySetIterator.hasNext()) { String key = keySetIterator.next(); String value = requestHe...
java
public Optional<Epic> getOptionalEpic(Object groupIdOrPath, Integer epicIid) { try { return (Optional.ofNullable(getEpic(groupIdOrPath, epicIid))); } catch (GitLabApiException glae) { return (GitLabApi.createOptionalFromException(glae)); } }
java
public static void registerReceiver(Context context, BroadcastReceiver receiver) { context.registerReceiver(receiver, new IntentFilter(ACTION_ACCESSORY_EVENT)); }
python
def drop_trailing_zeros(num): """ Drops the trailing zeros in a float that is printed. """ txt = '%f' %(num) txt = txt.rstrip('0') if txt.endswith('.'): txt = txt[:-1] return txt
python
def init(cls, name): """Return an instance of this class or an appropriate subclass""" clsdict = {subcls.name: subcls for subcls in cls.__subclasses__() if hasattr(subcls, 'name')} return clsdict.get(name, cls)(name)
java
static public Value getValue( Key key ) { Value val = DKV.get(key); return val; }
python
def add_feed(url): """add to db""" with Database("feeds") as db: title = feedparser.parse(url).feed.title name = str(title) db[name] = url return name
java
@Override public void remove() { try { removeThrow(); } catch (SQLException e) { closeQuietly(); // unfortunately, can't propagate back the SQLException throw new IllegalStateException("Could not delete " + dataClass + " object " + last, e); } }
python
def forward(self, x, boxes): """ Arguments: x (list[Tensor]): feature maps for each level boxes (list[BoxList]): boxes to be used to perform the pooling operation. Returns: result (Tensor) """ num_levels = len(self.poolers) rois = self....
java
public static String[] translatePathName(String path) { path = prettifyPath(path); if (path.indexOf('/') != 0) path = '/' + path; int index = path.lastIndexOf('/'); // remove slash at the end if (index == path.length() - 1) path = path.substring(0, path.length() - 1); index = path.lastIndexOf('/'); String name;...
python
def execute(self, command): """ Execute (or simulate) a command. Add to our log. @param command: Either a C{str} command (which will be passed to the shell) or a C{list} of command arguments (including the executable name), in which case the shell is not used. @r...
java
private String loadDrlFile(final Reader drl) throws IOException { final StringBuilder buf = new StringBuilder(); final BufferedReader input = new BufferedReader( drl ); String line; while ( (line = input.readLine()) != null ) { buf.append( line ); buf.append( nl )...
java
private void addLine(PdfLine line) { lines.add(line); contentHeight += line.height(); lastLine = line; this.line = null; }
python
def _perform_power_op(self, oper): """Perform requested power operation. :param oper: Type of power button press to simulate. Supported values: 'ON', 'ForceOff', 'ForceRestart' and 'Nmi' :raises: IloError, on an error from iLO. """ powe...
java
@Override public synchronized void open() throws IOException { if (_mode == Mode.OPEN) { return; } try { _addressArray.open(); _segmentManager.open(); _compactor.start(); init(); _mode = Mode.OPEN; ...
java
public void stop_logging () { Vector dl = Util.instance().get_device_list("*"); for (Object aDl : dl) { ((DeviceImpl) aDl).stop_logging(); } }
python
def memory_read_bytes(self, start_position: int, size: int) -> bytes: """ Read and return ``size`` bytes from memory starting at ``start_position``. """ return self._memory.read_bytes(start_position, size)
python
def flipcheck(content): """Checks a string for anger and soothes said anger Args: content (str): The message to be flipchecked Returns: putitback (str): The righted table or text """ # Prevent tampering with flip punct = """!"#$%&'*+,-./:;<=>?@[\]^_`{|}~ ━─""" tamperdict =...
java
public UpdateRulesOfIpGroupRequest withUserRules(IpRuleItem... userRules) { if (this.userRules == null) { setUserRules(new com.amazonaws.internal.SdkInternalList<IpRuleItem>(userRules.length)); } for (IpRuleItem ele : userRules) { this.userRules.add(ele); } ...
python
def p_binary_operators(self, p): """ conditional : conditional AND condition | conditional OR condition condition : condition LTE expression | condition GTE expression | condition LT expression | condition GT expre...
java
public IfcConstructionMaterialResourceTypeEnum createIfcConstructionMaterialResourceTypeEnumFromString( EDataType eDataType, String initialValue) { IfcConstructionMaterialResourceTypeEnum result = IfcConstructionMaterialResourceTypeEnum.get(initialValue); if (result == null) throw new IllegalArgumentExcep...
python
def parse_host_args(self, *args): """ Splits out the patch subcommand and returns a comma separated list of host_strings """ self.subcommand = None new_args = args try: sub = args[0] if sub in ['project','templates','static','media','wsgi','webconf...
java
@Override public void removeByCPOptionId(long CPOptionId) { for (CPOptionValue cpOptionValue : findByCPOptionId(CPOptionId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(cpOptionValue); } }
java
public static float max( float []array , int offset , int length ) { float max = -Float.MAX_VALUE; for (int i = 0; i < length; i++) { float tmp = array[offset+i]; if( tmp > max ) { max = tmp; } } return max; }
java
public boolean remove(SpdData data) { if (data == null) return false; if (data instanceof SpdDouble) { return super.remove(data); } else { return false; } }
python
def _vpn_signal_handler(self, args): """Called on NetworkManager PropertiesChanged signal""" # Args is a dictionary of changed properties # We only care about changes in ActiveConnections active = "ActiveConnections" # Compare current ActiveConnections to last seen ActiveConnecti...
java
boolean setParentNodeReference(N newParent, boolean fireEvent) { final N oldParent = getParentNode(); if (newParent == oldParent) { return false; } this.parent = (newParent == null) ? null : new WeakReference<>(newParent); if (!fireEvent) { return true; } firePropertyParentChanged(oldParent, newPare...
python
def ssh(self, *args, **kwargs): ''' Run salt-ssh commands synchronously Wraps :py:meth:`salt.client.ssh.client.SSHClient.cmd_sync`. :return: Returns the result from the salt-ssh command ''' ssh_client = salt.client.ssh.client.SSHClient(mopts=self.opts, ...
python
def fix_attr_encoding(ds): """ This is a temporary hot-fix to handle the way metadata is encoded when we read data directly from bpch files. It removes the 'scale_factor' and 'units' attributes we encode with the data we ingest, converts the 'hydrocarbon' and 'chemical' attribute to a binary integer ins...
java
@Override public InputHandler getInputHandler(ProtocolType type, SIBUuid8 sourceMEUuid, JsMessage msg) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "getInputHandler", new Object[] { type, sourceMEUuid, msg }); InputHandle...
python
def get_inline_views_from_fieldsets(fieldsets): """Returns a list of field names from an admin fieldsets structure.""" inline_views = [] for _, opts in fieldsets or (): if 'fieldsets' in opts: inline_views += get_inline_views_from_fieldsets(opts.get('fieldsets')) elif 'inline_vie...
python
def build_clonespec(config_spec, object_ref, reloc_spec, template): ''' Returns the clone spec ''' if reloc_spec.diskMoveType == QUICK_LINKED_CLONE: return vim.vm.CloneSpec( template=template, location=reloc_spec, config=config_spec, snapshot=objec...
python
def handle_noargs(self, **options): """ By default this function runs on all objects. As we are using a publishing system it should only update draft objects which can be modified in the tree structure. Once published the tree preferences should remain the same to ensur...
python
def get_tensor_size(self, tensor_name, partial_layout=None, mesh_dimension_to_size=None): """The size of a tensor in bytes. If partial_layout is specified, then mesh_dimension_to_size must also be. In this case, the size on a single device is returned. Args: tensor_name: a ...
java
public void walkSourceContents(SourceWalker walker) { for (int i = 0, len = this.children.size(); i < len; i++) { if (this.children.get(i) instanceof SourceNode) { ((SourceNode) this.children.get(i)).walkSourceContents(walker); } } for (Entry<String, Stri...
java
@Override public RegisterPatchBaselineForPatchGroupResult registerPatchBaselineForPatchGroup(RegisterPatchBaselineForPatchGroupRequest request) { request = beforeClientExecution(request); return executeRegisterPatchBaselineForPatchGroup(request); }
python
def items( self ): """ Returns all the rollout items for this widget. :return [<XRolloutItem>, ..] """ layout = self.widget().layout() return [layout.itemAt(i).widget() for i in range(layout.count()-1)]
java
public ArrayList<String> serviceName_networkInterfaceController_GET(String serviceName, OvhNetworkInterfaceControllerLinkTypeEnum linkType) throws IOException { String qPath = "/dedicated/server/{serviceName}/networkInterfaceController"; StringBuilder sb = path(qPath, serviceName); query(sb, "linkType", linkType)...
java
public Observable<RestorePointInner> createAsync(String resourceGroupName, String serverName, String databaseName, String restorePointLabel) { return createWithServiceResponseAsync(resourceGroupName, serverName, databaseName, restorePointLabel).map(new Func1<ServiceResponse<RestorePointInner>, RestorePointInner...
python
def lower(string): """Lower.""" new_string = [] for c in string: o = ord(c) new_string.append(chr(o + 32) if UC_A <= o <= UC_Z else c) return ''.join(new_string)
python
def nested(*contexts): """ Reimplementation of nested in python 3. """ with ExitStack() as stack: results = [ stack.enter_context(context) for context in contexts ] yield results
java
public java.util.List<NodeGroup> getNodeGroups() { if (nodeGroups == null) { nodeGroups = new com.amazonaws.internal.SdkInternalList<NodeGroup>(); } return nodeGroups; }
python
def on_train_begin(self, **kwargs): "Call watch method to log model topology, gradients & weights" # Set self.best, method inherited from "TrackerCallback" by "SaveModelCallback" super().on_train_begin() # Ensure we don't call "watch" multiple times if not WandbCallback.watch_c...
java
private void checkForFailure(Dependency[] dependencies) throws ScanAgentException { final StringBuilder ids = new StringBuilder(); for (Dependency d : dependencies) { boolean addName = true; for (Vulnerability v : d.getVulnerabilities()) { if (v.getCvssV2().getSco...
java
public BigMoney minus(Iterable<? extends BigMoneyProvider> moniesToSubtract) { BigDecimal total = amount; for (BigMoneyProvider moneyProvider : moniesToSubtract) { BigMoney money = checkCurrencyEqual(moneyProvider); total = total.subtract(money.amount); } re...
python
def run_psexec_command(cmd, args, host, username, password, port=445): ''' Run a command remotly using the psexec protocol ''' if has_winexe() and not HAS_PSEXEC: ret_code = run_winexe_command(cmd, args, host, username, password, port) return None, None, ret_code service_name = 'PS-E...
java
public static Packet decompress(final Packet packet) throws IOException { final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(packet.getData()); final GZIPInputStream gzipInputStream = new GZIPInputStream(byteArrayInputStream); final ByteArrayOutputStream byteArrayOut...
python
def sample(self, size=None): """ Sample from the prior distribution over datasets Args: size (Optional[int]): The number of samples to draw. Returns: array[n] or array[size, n]: The samples from the prior distribution over datasets. """ ...