language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public SqlBuilder where(String where) { if (StrUtil.isNotBlank(where)) { sql.append(" WHERE ").append(where); } return this; }
java
protected final Property parseVendorExtension( String vendorExtension ) { if (vendorExtension == null) return null; // Remove the curly braces ... String extension = vendorExtension.replaceFirst("^[{]", "").replaceAll("[}]$", ""); if (extension.trim().length() == 0) return null; ...
python
def add_service_subnet(self, context_id, subnet_id): """Adds a service subnet to a tunnel context. :param int context_id: The id-value representing the context instance. :param int subnet_id: The id-value representing the service subnet. :return bool: True if service subnet addition was...
python
def _loss_lr_subject(self, data, labels, w, theta, bias): """Compute the Loss MLR for a single subject (without regularization) Parameters ---------- data : array, shape=[voxels, samples] The fMRI data of subject i for the classification task. labels : array of int...
java
public static void removeWeakCounter(Cache<WeakCounterKey, CounterValue> cache, CounterConfiguration configuration, String counterName) { ByteString counterNameByteString = ByteString.fromString(counterName); for (int i = 0; i < configuration.concurrencyLevel(); ++i) { cache.remove(new Wea...
java
@Override public Connection connect(String url, Properties info) throws SQLException { if ("false".equals(info.get("javamelody"))) { // if property javamelody=false then it's not for us // (we pass here from the DriverManager.getConnection below) return null; } String myUrl = url; // we load f...
java
public static <T> boolean hasIntersection(T[] from, T[] target) { if (isEmpty(target)) { return true; } if (isEmpty(from)) { return false; } for (int i = 0; i < from.length; i++) { for (int j = 0; j < target.length; j++) { if ...
python
def __join_connections(self): """Wait for all connections to close. There are no side-effects here. We just want to try and leave -after- everything has closed, in general. """ interval_s = nsq.config.client.CONNECTION_CLOSE_AUDIT_WAIT_S graceful_wait_s = nsq.config.cl...
python
def get_checks( target_type=None, tags=None, ruleset_name=None, ruleset_file=None, ruleset=None, logging_level=logging.WARNING, checks_paths=None, skips=None, ): """ Get the sanity checks for the target. :param skips: name of checks to skip :param target_type: TargetType...
python
def _invoke(cls, cmd): """Invoke the given command, and return a tuple of process and raw binary output. stderr flows to wherever its currently mapped for the parent process - generally to the terminal where the user can see the error. :param list cmd: The command in the form of a list of strings ...
python
def find(self, objects): """Find exactly one match in the list of objects. :param objects: objects to filter :type objects: :class:`list` :return: the one matching object :raises groupy.exceptions.NoMatchesError: if no objects match :raises groupy.exceptions.MultipleMatc...
python
def extract_date(cls, date_str): """ Tries to extract a `datetime` object from the given string, expecting date information only. Raises `DateTimeFormatterException` if the extraction fails. """ if not date_str: raise DateTimeFormatterException('date_str must...
python
def diff(self, container): """ Inspect changes on a container's filesystem. Args: container (str): The container to diff Returns: (str) Raises: :py:class:`docker.errors.APIError` If the server returns an error. """ ...
java
public void setTerm(long term) { if (term > this.term) { this.term = term; this.leader = null; this.lastVotedFor = null; meta.storeTerm(this.term); meta.storeVote(this.lastVotedFor); log.debug("Set term {}", term); } }
python
def set_transfer_spec(self): ''' run the function to set the transfer spec on error set associated exception ''' _ret = False try: self._args.transfer_spec_func(self._args) _ret = True except Exception as ex: self.notify_exception(AsperaTransferSpecErr...
java
public static final int codePointAt(char[] text, int index) { char c1 = text[index++]; if (isHighSurrogate(c1)) { if (index < text.length) { char c2 = text[index]; if (isLowSurrogate(c2)) { return toCodePoint(c1, c2); } ...
java
public static ByteBuf copiedBuffer(ByteBuf buffer) { int readable = buffer.readableBytes(); if (readable > 0) { ByteBuf copy = buffer(readable); copy.writeBytes(buffer, buffer.readerIndex(), readable); return copy; } else { return EMPTY_BUFFER; ...
java
public Response createSystemProperty(SystemProperty property) { return restClient.post("system/properties", property, new HashMap<String, String>()); }
java
private void restoreNestedVariables() { if (nestedVars != null) { Iterator iter = nestedVars.iterator(); while (iter.hasNext()) { String varName = (String) iter.next(); varName = findAlias(varName); Object obj = originalNestedVars.get(varName); if (obj != null) { invokingJspCtxt.setAttribute(va...
java
@Override public ListEndpointGroupsResult listEndpointGroups(ListEndpointGroupsRequest request) { request = beforeClientExecution(request); return executeListEndpointGroups(request); }
java
public static void write(final X509Certificate certificate, final @NonNull OutputStream outputStream, KeyFileFormat fileFormat) throws IOException, CertificateEncodingException { final byte[] certificateBytes = certificate.getEncoded(); switch (fileFormat) { case PEM : outputStream.write( Certifi...
java
public ViewHolder findViewHolderForItemId(long id) { final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final ViewHolder holder = getChildViewHolderInt(getChildAt(i)); if (holder != null && holder.getItemId() == id) { return holder; ...
python
def del_variables(self, variables): """ Deletes variables from the NoisyOrModel. Parameters ---------- variables: list, tuple, dict (array like) list of variables to be deleted. Examples -------- >>> from pgmpy.models import NoisyOrModel ...
python
def remove_layer(svg_source, layer_name): ''' Remove layer(s) from SVG document. Arguments --------- svg_source : str or file-like A file path, URI, or file-like object. layer_name : str or list Layer name or list of layer names to remove from SVG document. Returns ----...
java
@Remote @Produces public <K, V> RemoteCache<K, V> getRemoteCache(InjectionPoint injectionPoint) { final Set<Annotation> qualifiers = injectionPoint.getQualifiers(); final RemoteCacheManager cacheManager = getRemoteCacheManager(qualifiers.toArray(new Annotation[0])); final Remote remote = getRemo...
python
def add_widget(self, widget): """ Add a Widget as a managed child of this Widget. The child will be automatically positioned and sized to fill the entire space inside this Widget (unless _update_child_widgets is redefined). Parameters ---------- widget :...
python
def close(self): """Close the connection to memcached, if it is open. The next call to a method that requires a connection will re-open it.""" if self.sock is not None: try: self.sock.close() except Exception: pass finally: ...
java
protected boolean readPacket () throws IOException { int result; while ((result = _stream.packetout(_packet)) != 1) { if (result == 0 && !readPage()) { return false; } } return true; }
python
def reverse_shortlex(end, other, excludeend=False): """Yield all intersections of end with other in reverse shortlex order. >>> ['{:03b}'.format(s) for s in reverse_shortlex(0b111, [0b011, 0b101, 0b110])] ['111', '011', '101', '110', '001', '010', '100', '000'] >>> ', '.join(''.join(sorted(s)) ......
python
def get_config_section(self, name): """ Get a section of a configuration """ if self.config.has_section(name): return self.config.items(name) return []
python
def convert_dict_to_params(src_dict): """ convert dict to params string Args: src_dict (dict): source mapping data structure Returns: str: string params data Examples: >>> src_dict = { "a": 1, "b": 2 } >>> convert_dict_to_params(src_dict...
python
def fqn(self): ''' Returns a fully qualified name for this object ''' prefix = type(self).cls_key() return '{}:{}'.format(prefix, self.id)
java
private void deleteAllTraits(AtlasVertex instanceVertex) throws AtlasBaseException { List<String> traitNames = GraphHelper.getTraitNames(instanceVertex); LOG.debug("Deleting traits {} for {}", traitNames, string(instanceVertex)); String typeName = GraphHelper.getTypeName(instanceVertex); ...
java
private static String getTypeDeprecationInfo(JSType type) { if (type == null) { return null; } String depReason = getDeprecationReason(type.getJSDocInfo()); if (depReason != null) { return depReason; } ObjectType objType = castToObject(type); if (objType != null) { Object...
python
def array_convert_function(sshape_one, sshape_two, variables): """ Return a function defining the conversion process between two NumPy arrays of different shapes """ if not isinstance(sshape_one, tuple): sshape_one = (sshape_one,) if not isinstance(sshape_two, tuple): sshape_two = (sshape_two,) s_o...
python
def find_library(series_path): """Search for the location of a series within the library. :param str series_path: name of the relative path of the series :returns: library path :rtype: str """ for location in cfg.CONF.libraries: if os.path.isdir(os.path.join(location, series_path)): ...
python
def _value_to_python(value): """Converts a google.protobuf.Value to a native Python object.""" assert isinstance(value, struct_pb2.Value) field = value.WhichOneof('kind') if field == 'number_value': return value.number_value elif field == 'string_value': return value.string_value elif field == 'boo...
java
@Override public void eUnset(int featureID) { switch (featureID) { case AfplibPackage.ERS__RS_NAME: setRSName(RS_NAME_EDEFAULT); return; } super.eUnset(featureID); }
java
public <T extends Annotation> T getControlAnnotation(Class<T> annotationClass) { Class controlInterface = getControlType(); return (T)controlInterface.getAnnotation(annotationClass); }
python
def do_gen(argdict): '''Generate the whole site.''' site = make_site_obj(argdict) try: st = time.time() site.generate() et = time.time() print "Generated Site in %f seconds."% (et-st) except ValueError as e: # pragma: no cover print "Cannot generate. You are not w...
python
def mixin_params(self, params): """ Merge in the MdsolAttribute for the passed parameter :param dict params: dictionary of object parameters """ if not isinstance(params, (dict,)): raise AttributeError("Cannot mixin to object of type {}".format(type(params))) ...
java
public void setInputType(InputType input) { if (this.stateMachine.currentMissionBehaviour() != null && this.stateMachine.currentMissionBehaviour().commandHandler != null) this.stateMachine.currentMissionBehaviour().commandHandler.setOverriding(input == InputType.AI); if (this.mouseHook != null) ...
python
def _parse_memory_embedded_health(self, data): """Parse the get_host_health_data() for essential properties :param data: the output returned by get_host_health_data() :returns: memory size in MB. :raises IloError, if unable to get the memory details. """ memory_mb = 0 ...
python
def _redact_secret( data: Union[Dict, List], ) -> Union[Dict, List]: """ Modify `data` in-place and replace keys named `secret`. """ if isinstance(data, dict): stack = [data] else: stack = [] while stack: current = stack.pop() if 'secret' in current: ...
java
public static String getComponentProjectName(int componentType, String groupId, String artifactId) { IModel m = ModelFactory.newModel(groupId, artifactId, null, null, MuleVersionEnum.MAIN_MULE_VERSION, null, null); String projectFolderName = null; ComponentEnum compEnum = ComponentEnum.get(componentType); switc...
java
public void addProperty(final FedoraResource resource, final org.apache.jena.rdf.model.Property predicate, final RDFNode value, final Map<String, String> namespaces) throws RepositoryException { addProperty(resource, predicate, value, namespaces, false); }
java
@Override public boolean eIsSet(int featureID) { switch (featureID) { case AfplibPackage.CPIRG__GCGID: return GCGID_EDEFAULT == null ? gcgid != null : !GCGID_EDEFAULT.equals(gcgid); case AfplibPackage.CPIRG__PRT_FLAGS: return PRT_FLAGS_EDEFAULT == null ? prtFlags != null : !PRT_FLAGS_EDEFAULT.equals(pr...
python
def send_sticker(self, sticker: str, reply: Message=None, on_success: callable=None, reply_markup: botapi.ReplyMarkup=None): """ Send sticker to this peer. :param sticker: File path to sticker to send. :param reply: Message object. :param on_success: Callback...
java
@Nonnull public TypeaheadDataset setHeader (@Nullable final IHCNode aHeader) { return setHeader (aHeader != null ? HCRenderer.getAsHTMLStringWithoutNamespaces (aHeader) : (String) null); }
java
private Date getTime(String value) throws MPXJException { try { Number hours = m_twoDigitFormat.parse(value.substring(0, 2)); Number minutes = m_twoDigitFormat.parse(value.substring(2, 4)); Calendar cal = DateHelper.popCalendar(); cal.set(Calendar.HOUR_OF_DAY, hours.i...
python
def add_coupon(self, coupon, idempotency_key=None): """ Add a coupon to a Customer. The coupon can be a Coupon object, or a valid Stripe Coupon ID. """ if isinstance(coupon, StripeModel): coupon = coupon.id stripe_customer = self.api_retrieve() stripe_customer["coupon"] = coupon stripe_customer.sav...
python
def genlmsg_valid_hdr(nlh, hdrlen): """Validate Generic Netlink message headers. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/genl.c#L117 Verifies the integrity of the Netlink and Generic Netlink headers by enforcing the following requirements: - Valid Netlink message header (`nlmsg_vali...
python
def composition_prediction(self, composition, to_this_composition=True): """ Returns charged balanced substitutions from a starting or ending composition. Args: composition: starting or ending composition to_this_composition: If tr...
python
def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The...
python
def imbtree(ntips, treeheight=1.0): """ Return an imbalanced (comb-like) tree topology. """ rtree = toytree.tree() rtree.treenode.add_child(name="0") rtree.treenode.add_child(name="1") for i in range(2, ntips): # empty node cherry = toytre...
python
def setVisible(self, state): """ Closes this widget and kills the result. """ super(XOverlayWidget, self).setVisible(state) if not state: self.setResult(0)
python
def get_calendar_entries(context, year=None, month=None, template='zinnia/tags/entries_calendar.html'): """ Return an HTML calendar of entries. """ if not (year and month): day_week_month = (context.get('day') or context.get('week') or ...
java
@BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings("unchecked") public static <T> Flowable<T> concatArray(MaybeSource<? extends T>... sources) { ObjectHelper.requireNonNull(sources, "sources is null"); if (sources.leng...
python
def call_spellchecker(cmd, input_text=None, encoding=None): """Call spell checker with arguments.""" process = get_process(cmd) # A buffer has been provided if input_text is not None: for line in input_text.splitlines(): # Hunspell truncates lines at `0x1fff` (at least on Windows t...
java
public DerInputStream subStream(int len, boolean do_skip) throws IOException { DerInputBuffer newbuf = buffer.dup(); newbuf.truncate(len); if (do_skip) { buffer.skip(len); } return new DerInputStream(newbuf); }
java
private TopHitsBuilder getTopHitsAggregation(SelectStatement selectStatement, Integer size, EntityMetadata entityMetadata) { TopHitsBuilder topHitsBuilder = AggregationBuilders.topHits(ESConstants.TOP_HITS); if (size != null) { topHitsBuilder.setSize(size); } ...
python
def get(self, request, pk=None): """ Handles GET requests. """ self.top_level_forum = get_object_or_404(Forum, pk=pk) if pk else None return super().get(request, pk)
java
public synchronized DownloadResponse getJnlpFileEx( JnlpResource jnlpres, DownloadRequest dreq ) throws IOException { String path = jnlpres.getPath(); URL resource = jnlpres.getResource(); long lastModified = jnlpres.getLastModified(); _log.addDebug( "lastModified: " + l...
python
def from_meta(cls, meta: "DocstringMeta") -> T.Any: """Copy DocstringMeta from another instance.""" return cls(args=meta.args, description=meta.description)
java
public List<String> getKeys(String prefix) { return IteratorUtils.toList(configuration.getKeys(prefix)); }
java
protected static org.neo4j.graphdb.Node createTemplateItemNode( final AbstractGraphDatabase graphDatabase, final TemplateItemInfo itemInfo) { final org.neo4j.graphdb.Node itemNode = graphDatabase.createNode(); itemNode.setProperty(TemplateXMLFields.ITEM_NAME, itemInfo.getName()); return itemNode; }
python
def create_router(self, context, router): """Creates a router on Arista Switch. Deals with multiple configurations - such as Router per VRF, a router in default VRF, Virtual Router in MLAG configurations """ if router: router_name = self._arista_router_name(router['i...
python
def join(self, timeout: Union[float, datetime.timedelta] = None) -> Awaitable[None]: """Block until all items in the queue are processed. Returns an awaitable, which raises `tornado.util.TimeoutError` after a timeout. """ return self._finished.wait(timeout)
java
private CmsContextMenuItemWidget createEmptyItemWidget( String id, String caption, String description, CmsContextMenuConnector contextMenuConnector) { CmsContextMenuItemWidget widget = GWT.create(CmsContextMenuItemWidget.class); widget.setId(id); widget.s...
python
def optimize(self, x0, target): """Calculate an optimum argument of an objective function.""" x = x0 for _ in range(self.maxiter): delta = np.linalg.solve(self.h(x, target), -self.g(x, target)) x = x + delta if np.linalg.norm(delta) < self.tol: ...
python
def wms_vrt(wms_file, bounds=None, resolution=None): """Make a VRT XML document from a wms file. Parameters ---------- wms_file : str The source wms file bounds : GeoVector, optional The requested footprint of the generated VRT resolution : float, optional The requested r...
java
public void setXftUnits(Integer newXftUnits) { Integer oldXftUnits = xftUnits; xftUnits = newXftUnits; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.FNC__XFT_UNITS, oldXftUnits, xftUnits)); }
java
public static void main(String[] args) { LOVEndpoint lov = new LOVEndpoint(); String file = args.length > 0 ? args[1].trim() : "rdfunit-model/src/main/resources/org/aksw/rdfunit/configuration/schemaLOV.csv"; lov.writeAllLOVEntriesToFile(file); }
python
def almost_equal_elem(self,other,tol,relative=True): """ Compare whether two array types are almost equal, element by element. If the 'relative' parameter is 'True' (the default) then the 'tol' parameter (which must be positive) is interpreted as a relative tolerance, an...
python
def values_for_column(self, column_name, limit=10000): """Runs query against sqla to retrieve some sample values for the given column. """ cols = {col.column_name: col for col in self.columns} target_col = cols[column_name] tp = self.get_template_processor() qry ...
java
public AndCondition optimize() { AndCondition result = new AndCondition(); for (Condition each : conditions) { if (Condition.class.equals(each.getClass())) { result.getConditions().add(each); } } if (result.getConditions().isEmpty()) { ...
python
def map(cls, latitudes, longitudes, labels=None, colors=None, areas=None, **kwargs): """Return markers from columns of coordinates, labels, & colors. The areas column is not applicable to markers, but sets circle areas. """ assert len(latitudes) == len(longitudes) assert areas i...
java
public boolean isLockSupported(int idx) throws IOException { StorageDirectory sd = storageDirs.get(idx); FileLock firstLock = null; FileLock secondLock = null; try { firstLock = sd.lock; if(firstLock == null) { firstLock = sd.tryLock(); if(firstLock == null) return ...
java
@RequirePOST public void doCreateAccountByAdmin(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { createAccountByAdmin(req, rsp, "addUser.jelly", "."); // send the user back to the listing page on success }
java
private void updateActivity(ActivityType type, String name, String streamingUrl) { if (name == null) { activity = null; } else if (streamingUrl == null) { activity = new ActivityImpl(type, name, null); } else { activity = new ActivityImpl(type, name, streaming...
java
@Override public void print(MoneyPrintContext context, Appendable appendable, BigMoney money) throws IOException { MoneyFormatter fmt = (money.isZero() ? whenZero : money.isPositive() ? whenPositive : whenNegative); fmt.getPrinterParser().print(context, appendable, money); }
java
protected void processGossipResponse(Tree data) throws Exception { // Debug if (debugHeartbeats) { String sender = data.get("sender", (String) null); logger.info("Gossip response received from \"" + sender + "\" node:\r\n" + data); } // Online / offline nodes in responnse Tree online = data.get("onlin...
python
def _finalize_block_blob(self, sd, metadata, digest): # type: (SyncCopy, blobxfer.models.synccopy.Descriptor, dict, # str) -> None """Finalize Block blob :param SyncCopy self: this :param blobxfer.models.synccopy.Descriptor sd: synccopy descriptor :param dict metad...
python
def get_conditions(self): """ get conditions through which the pod has passed :return: list of PodCondition enum or empty list """ # filter just values that are true (means that pod has that condition right now) return [PodCondition.get_from_string(c.type) for c in self....
python
def prefix(tokens, operator_table): """Match a prefix of an operator.""" operator, matched_tokens = operator_table.prefix.match(tokens) if operator: return TokenMatch(operator, None, matched_tokens)
java
public static String escape(final String url, final boolean strict) { return (strict ? STRICT_ESCAPER : ESCAPER).escape(url); }
python
def pbkdf2_hex(data, salt, iterations=DEFAULT_PBKDF2_ITERATIONS, keylen=None, hashfunc=None): """Like :func:`pbkdf2_bin` but returns a hex encoded string. .. versionadded:: 0.9 :param data: the data to derive. :param salt: the salt for the derivation. :param iterations: the number o...
python
def pretty_list(rtlst, header, sortBy=0, borders=False): """Pretty list to fit the terminal, and add header""" if borders: _space = "|" else: _space = " " # Windows has a fat terminal border _spacelen = len(_space) * (len(header) - 1) + (10 if WINDOWS else 0) _croped = False ...
python
def show_graph(self, format='svg'): """ Render this Pipeline as a DAG. Parameters ---------- format : {'svg', 'png', 'jpeg'} Image format to render with. Default is 'svg'. """ g = self.to_simple_graph(AssetExists()) if format == 'svg': ...
java
public Statistics columnDistinctCount(String columnName, Long ndv) { this.columnStats .computeIfAbsent(columnName, column -> new HashMap<>()) .put(DISTINCT_COUNT, String.valueOf(ndv)); return this; }
java
public static void disableDoubleBuffering(Component c) { RepaintManager currentManager = RepaintManager.currentManager(c); currentManager.setDoubleBufferingEnabled(false); }
java
public static <T> Set<T> cast(Set<?> set) { return set == null ? null : new CastingSet<T>(set); }
python
def form_invalid(self, form): """Override of CreateView method, logs invalid email form submissions.""" LOGGER.debug("Invalid Email Form Submitted") messages.add_message(self.request, messages.ERROR, _("Invalid Email Address.")) return super(EmailTermsView, self).form_invalid(form)
java
@Nonnull @OverrideOnDemand protected TOOLBAR_TYPE createCreateToolbar (@Nonnull final WPECTYPE aWPEC, @Nonnull final FORM_TYPE aForm, @Nullable final DATATYPE aSelectedObject) { final Locale aDisplayLocale = aWPEC.getD...
python
async def get_version(self, tp, params): """ Loads version from the stream / version database # TODO: instance vs. tp. :param tp: :param params: :return: """ tw = TypeWrapper(tp, params) if not tw.is_versioned(): # self.registry.set_tr...
python
def primary_dimensions(self): """Iterate over the primary dimension columns, columns which do not have a parent """ from ambry.valuetype.core import ROLE for c in self.columns: if not c.parent and c.role == ROLE.DIMENSION: yield c
python
def _get_export_mgr(self): """ Returns: (DiskExportManager): Handler for each disk """ return ( DiskExportManager.get_instance_by_type( dst=self._dst, disk=disk, do_compress=self._compress, *self._arg...
python
def _count_files_to_amber(tumor_counts, normal_counts, work_dir, data): """Converts tumor and normal counts from GATK CollectAllelicCounts into Amber format. """ amber_dir = utils.safe_makedir(os.path.join(work_dir, "amber")) out_file = os.path.join(amber_dir, "%s.amber.baf" % dd.get_sample_name(data)) ...
java
public static <S, I, O> ADTNode<S, I, O> buildFromADS(final ADSNode<S, I, O> node) { if (node.isLeaf()) { return new ADTLeafNode<>(null, node.getHypothesisState()); } final ADTNode<S, I, O> result = new ADTSymbolNode<>(null, node.getSymbol()); for (Map.Entry<O, ADSNode<S, ...
java
public Collection<AlertViolation> list(List<String> queryParams) { return HTTP.GET("/v2/alerts_violations.json", null, queryParams, ALERT_VIOLATIONS).get(); }