language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public <T> List<T> callForList(Class<T> resultClass, String functionName){ String sql = toCallString(functionName, true); return callExecutor.callForList(resultClass, sql); }
python
def pop(self): """Pop an entry off the stack and make its node a child of the last.""" dfa, state, node = self.stack.pop() if self.stack: self.stack[-1][2].children.append(node) else: self.root = node
python
def add_layer_from_yaml_file(self, filename): """This function implements loading a YAML file and populating a new empty layer (Layer) with its contents :param filename: The name of a file to read :type filename: string """ if filename.endswith(('.yaml', '.yml')): ...
python
def discr_sequence_space(shape, dtype=None, impl='numpy', **kwargs): """Return an object mimicing the sequence space ``l^p(R^d)``. The returned object is a `DiscreteLp` on the domain ``[0, shape - 1]``, using a uniform grid with stride 1. Parameters ---------- shape : int or sequence of ints ...
python
def write_to_collection_from_addon(self): """ Write to local collection. *Only usable when running inside an Anki addon!* Only tested on Anki 2.1. This writes to a temporary file and then calls the code that Anki uses to import packages. Note: the caller may want to use mw.checkpoint and mw.reset as f...
java
public static <T> Optional<T> getOptionalUnsafe(final Map map, final Class<T> clazz, final Object... path) { return getUnsafe(map, Optional.class, path); }
python
def focusd(task): """ Forks the current process as a daemon to run a task. `task` ``Task`` instance for the task to run. """ # determine if command server should be started if registration.get_registered(event_hooks=True, root_access=True): # root event plugins availabl...
java
public void setPolicyTypeDescriptions(java.util.Collection<PolicyTypeDescription> policyTypeDescriptions) { if (policyTypeDescriptions == null) { this.policyTypeDescriptions = null; return; } this.policyTypeDescriptions = new com.amazonaws.internal.SdkInternalList<Policy...
python
def find_node(self, x: int, y: int) -> Optional["BSP"]: """Return the deepest node which contains these coordinates. Returns: Optional[BSP]: BSP object or None. """ if not self.contains(x, y): return None for child in self.children: found = ch...
java
@Override public int doEndTag() throws JspException { String result; // the eventual result // add (already encoded) parameters String baseUrl = resolveUrl(value, context, pageContext); result = params.aggregateParams(baseUrl); // if the URL is relative, rewr...
python
def load_from_file(module_path): """ Load a python module from its absolute filesystem path Borrowed from django-cms """ from imp import load_module, PY_SOURCE imported = None if module_path: with open(module_path, 'r') as openfile: imported = load_module('mod', openfil...
java
public static<T> Vendor<T> vendor(Callable<T> f) { return j.vendor(f); }
java
@Override public OutputHandler choosePtoPOutputHandler(SIBUuid8 fixedMEUuid, SIBUuid8 preferredMEUuid, boolean localMessage, boolean forcePut, ...
java
public static int damerauLevenshteinDistance(String str1, String str2) { // return fast if one or both strings is empty or null if ((str1 == null) || str1.isEmpty()) { if ((str2 == null) || str2.isEmpty()) { return 0; } else { return str2.length();...
python
def get_software_info(self): """Return the current software status.""" self.request(EP_GET_SOFTWARE_INFO) return {} if self.last_response is None else self.last_response.get('payload')
python
def show_shortcuts(self, menu): """Show action shortcuts in menu""" for element in getattr(self, menu + '_menu_actions'): if element and isinstance(element, QAction): if element._shown_shortcut is not None: element.setShortcut(element._shown_shortcut)
python
def apply_transformer_t_model(network): """Convert given T-model parameters to PI-model parameters using wye-delta transformation""" z_series = network.transformers.r_pu + 1j*network.transformers.x_pu y_shunt = network.transformers.g_pu + 1j*network.transformers.b_pu ts_b = (network.transformers.model...
java
@Override public final Throwable setUncheckedException(EJSDeployedSupport s, Throwable ex) // d395666 { // d161864 Begins if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, "setUncheckedException in param:" + ex); //150727 } // d161864 End...
python
def chain(args): """ %prog chain blastfile Chain adjacent HSPs together to form larger HSP. """ p = OptionParser(chain.__doc__) p.add_option("--dist", dest="dist", default=100, type="int", help="extent of flanking regions to search [default: %default]") opts, args =...
python
def parse_ltv_packet(packet): """Parse a tag-length-value style beacon packet.""" try: frame = LTVFrame.parse(packet) for ltv in frame: if ltv['type'] == SERVICE_DATA_TYPE: data = ltv['value'] if data["service_identifier"] == EDDYSTONE_UUID: ...
python
def get_option_int(self, name, section=None, vars=None, expect=None): """Just like ``get_option`` but parse as an integer.""" val = self.get_option(name, section, vars, expect) if val: return int(val)
java
@Override public void error(AuthzTrans trans, HttpServletResponse response, Result<?> result) { String msg = result.details==null?"%s":"%s - " + result.details.trim(); String msgId; String[] detail; if(result.variables==null) { detail = new String[1]; } else { int l = result.variables.length; ...
java
public InputStream executeWithoutAccessCheck() throws EFapsException { InputStream ret = null; executeEvents(EventType.CHECKOUT_PRE); if (!executeEvents(EventType.CHECKOUT_OVERRIDE)) { ret = this.executeWithoutTrigger(); } executeEvents(EventType.CHECKOUT_...
java
public static String identityToString(Object object) { if (object == null) { return null; } StringBuffer buffer = new StringBuffer(); identityToString(buffer, object); return buffer.toString(); }
java
public void addMappingTarget(String mapping, RequestProcessor target) throws Exception { context.addMappingTarget(mapping, target); }
java
public synchronized int addObject(Object object) throws ConversationStateFullException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "addObject", "object=" + object); int objectIndex = 0; if (freeSlot == MINUS_ONE) { // Object ...
java
private int[] determinePower2Alpha_Buckets_Sarray_Sptrmap(int q) { int strLen = length; int exp2 = kbs_getExp_Ulong(2, alphabet.size); if (exp2 < 0) { throw new RuntimeException("value out of bounds"); } int[] buckets = determinePower2Alpha_Buckets_Sarray(q); ...
python
def cleanup_sent_messages(ago=None, dispatches_only=False): """Cleans up DB : removes delivered dispatches (and messages). :param int ago: Days. Allows cleanup messages sent X days ago. Defaults to None (cleanup all sent). :param bool dispatches_only: Remove dispatches only (messages objects will stay inta...
java
@Override public void onProcessUnstructuredSSRequest(ProcessUnstructuredSSRequest procUnstrReqInd) { // NetworkIdState networkIdState = this.mapStack.getMAPProvider().getNetworkIdState(0); // if (!(networkIdState == null || networkIdState.isAvailavle() && networkIdState.getCongLevel() == 0)) { // ...
python
def getKneeEstimateDistance(cell_barcode_counts, cell_number=False, plotfile_prefix=None): ''' estimate the number of "true" cell barcodes via a knee method which finds the point with maximum distance input: cell_barcode_counts = dict(key = b...
python
def _LoadAuditEvents(handlers, get_report_args, actions=None, token=None, transformers=None): """Returns AuditEvents for given handlers, actions, and timerange.""" if transformers is None: transformers = {} if data_store.Rela...
java
@Override public Long touch(final byte[]... keys) { checkIsInMultiOrPipeline(); client.touch(keys); return client.getIntegerReply(); }
java
public int getNumberOfAttempts() { String value = Optional.fromNullable(getParameter(SignalParameters.NUMBER_OF_ATTEMPTS.symbol())).or("1"); return Integer.parseInt(value); }
python
def register_watchers(self, type_callback_dict, register_timeout=None): """ Register multiple callback/event type pairs, expressed as a dict. """ for event_type, callback in type_callback_dict.items(): self._push_watchers[event_type].add(callback) self.wait_for_respon...
python
def declareLegacyItem(typeName, schemaVersion, attributes, dummyBases=()): """ Generate a dummy subclass of Item that will have the given attributes, and the base Item methods, but no methods of its own. This is for use with upgrading. @param typeName: a string, the Axiom TypeName to have attribut...
java
public void marshall(GetEffectivePoliciesRequest getEffectivePoliciesRequest, ProtocolMarshaller protocolMarshaller) { if (getEffectivePoliciesRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshal...
java
@Override protected void DecodeFromCBORObject(CBORObject messageObject) throws CoseException { if (messageObject.size() != 4) throw new CoseException("Invalid Sign1 structure"); if (messageObject.get(0).getType() == CBORType.ByteString) { rgbProtected = messageObject.get(0).GetB...
java
public static String checkSameNameFeatureTypeStyle( List<FeatureTypeStyleWrapper> ftsWrapperList, String ftsName ) { int index = 1; String name = ftsName.trim(); for( int i = 0; i < ftsWrapperList.size(); i++ ) { FeatureTypeStyleWrapper ftsWrapper = ftsWrapperList.get(i); ...
python
def child(self,index): "helper for __getitem__/__setitem__" if isinstance(index,tuple): attr,i = index return getattr(self,attr)[i] else: return getattr(self,index)
java
public void setVisibleData(final VisibleData VISIBLE_DATA) { if (null == visibleData) { _visibleData = VISIBLE_DATA; redraw(); } else { visibleData.set(VISIBLE_DATA); } }
java
public boolean ping(final String anode, final long timeout) { if (anode.equals(node)) { return true; } else if (anode.indexOf('@', 0) < 0 && anode.equals(node.substring(0, node.indexOf('@', 0)))) { return true; } // other node OtpMbox mbox...
java
@SuppressWarnings("unchecked") public T getDefaultObject() { if(defaultValue instanceof IModel) { return ((IModel<T>)defaultValue).getObject(); } else { return (T) defaultValue; } }
python
def build(self, builder, formname=None): """Build XML by appending to builder""" params = dict(ItemGroupOID=formname if formname else self.itemgroupoid) if self.transaction_type is not None: params["TransactionType"] = self.transaction_type if self.item_group_repeat_key is...
python
def GenesisBlock() -> Block: """ Create the GenesisBlock. Returns: BLock: """ prev_hash = UInt256(data=bytearray(32)) timestamp = int(datetime(2016, 7, 15, 15, 8, 21, tzinfo=pytz.utc).timestamp()) index = 0 consensus_data = 2083236893 # Pay t...
java
public void cancelOrder(KiteConnect kiteConnect) throws KiteException, IOException { // Order modify request will return order model which will contain only order_id. // Cancel order will return order model which will only have orderId. Order order2 = kiteConnect.cancelOrder("180116000727266", C...
python
def fromrandom(shape=(10, 50, 50), npartitions=1, seed=42, engine=None): """ Generate random image data. Parameters ---------- shape : tuple, optional, default=(10, 50, 50) Dimensions of images. npartitions : int, optional, default=1 Number of partitions. seed : int, optio...
python
def close(self): """ Closes the device. """ try: # TODO: Find a way to speed up this shutdown. if self.ssl: self._device.shutdown() else: # Make sure that it closes immediately. self._device.shutdown(soc...
java
public static boolean shouldUnwrap(Class<? extends Exception> c) { return c.equals(CompletionException.class) || c.equals(ExecutionException.class); }
python
def _inject(): """ Inject functions and constants from PyOpenGL but leave out the names that are deprecated or that we provide in our API. """ # Get namespaces NS = globals() GLNS = _GL.__dict__ # Get names that we use in our API used_names = [] used_names.extend([names[0] ...
python
def _save(self, hdf5, model, positives, negatives): """Saves the given intermediate state of the bootstrapping to file.""" # write the model and the training set indices to the given HDF5 file hdf5.set("PositiveIndices", sorted(list(positives))) hdf5.set("NegativeIndices", sorted(list(negatives))) h...
python
def makebunches_alter(data, commdct, theidf): """make bunches with data""" bunchdt = {} dt, dtls = data.dt, data.dtls for obj_i, key in enumerate(dtls): key = key.upper() objs = dt[key] list1 = [] for obj in objs: bobj = makeabunch(commdct, obj, obj_i) ...
java
@CheckReturnValue public FluentGenerator<T> filter(@Nonnull Predicate<T> predicate) { return from(new FilteringGenerator<>(delegate, checkNotNull(predicate))); }
java
public void include(Object it, String view) throws IOException, JellyException { _include(it,request.getWebApp().getKlass(it),view); }
java
public Response updateUser(UserEntity userEntity) { return restClient.put("users/" + userEntity.getUsername(), userEntity, new HashMap<String, String>()); }
python
def raw(self): # type: () -> ClientRawResponse """Get current page as ClientRawResponse. :rtype: ClientRawResponse """ raw = ClientRawResponse(self.current_page, self._response) if self._raw_headers: raw.add_headers(self._raw_headers) return raw
python
def subscribe(self, subscription_channel, **observer_params): """Subscribe to a channel This adds a channel to the router, configures it, starts it, and returns its observer """ return self.get_channel(subscription_channel, **observer_params).ensure_started().observer
python
def list_from_tibiadata(cls, content): """Parses the content of a house list from TibiaData.com into a list of houses Parameters ---------- content: :class:`str` The raw JSON response from TibiaData Returns ------- :class:`list` of :class:`ListedHous...
python
def cache_delsite(site_id): 'Removes all cache data from a site.' mkey = getkey(T_META, site_id) tmp = cache.get(mkey) if not tmp: return for tkey in tmp: cache.delete(tkey) cache.delete(mkey)
python
def replace_namespaced_lease(self, name, namespace, body, **kwargs): # noqa: E501 """replace_namespaced_lease # noqa: E501 replace the specified Lease # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=Tru...
python
def _call_api(self, http_method, url, **kwargs): """ Execute a call to the Zendesk API. Handles rate limiting, checking the response from Zendesk and deserialization of the Zendesk response. All communication with Zendesk should go through this method. :param http_method: The re...
java
private void drainPendingCalls() { assert realStream != null; assert !passThrough; List<Runnable> toRun = new ArrayList<>(); DelayedStreamListener delayedListener = null; while (true) { synchronized (this) { if (pendingCalls.isEmpty()) { pendingCalls = null; passThr...
java
protected void setIconActions(CmsListColumnDefinition iconCol) { // add resource icon action CmsListDirectAction resourceIconAction = new CmsDependencyIconAction( LIST_ACTION_ICON, CmsDependencyIconActionType.RESOURCE, getCms()); resourceIconAction.setName(Me...
java
public static <T> T getPrevInstruction(InstructionHandle startHandle, Class<T> clazz) { InstructionHandle curHandle = startHandle; while (curHandle != null) { curHandle = curHandle.getPrev(); if (curHandle != null && clazz.isInstance(curHandle.getInstruction())) { ...
java
@Override public List<CommerceTaxFixedRateAddressRel> findByCPTaxCategoryId( long CPTaxCategoryId) { return findByCPTaxCategoryId(CPTaxCategoryId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); }
java
public T put(String key, T value) { return container.put(key, value); }
java
public void setMatchingEventTypes(java.util.Collection<String> matchingEventTypes) { if (matchingEventTypes == null) { this.matchingEventTypes = null; return; } this.matchingEventTypes = new com.amazonaws.internal.SdkInternalList<String>(matchingEventTypes); }
java
private void findArchiveFiles() { clearArcives(); // path should be optionally configurable File cachePaths = Configuration.getInstance().getOsmdroidBasePath(); final File[] files = cachePaths.listFiles(); if (files != null) { for (final File file : files) { ...
java
@Override public DeletePendingAggregationRequestResult deletePendingAggregationRequest(DeletePendingAggregationRequestRequest request) { request = beforeClientExecution(request); return executeDeletePendingAggregationRequest(request); }
java
static JSBoxedListImpl create(JSVaryingList subList, int subAccessor) { if (subList.getIndirection() > 0) return new JSIndirectBoxedListImpl(subList, subAccessor); else return new JSBoxedListImpl(subList, subAccessor); }
java
public boolean startSubsystem(String subsystem) throws SshException { ByteArrayWriter request = new ByteArrayWriter(); try { request.writeString(subsystem); boolean success = sendRequest("subsystem", true, request.toByteArray()); if (success) { EventServiceImplementation.getInstance().fireEvent(...
java
private int serialize(final int activePathIndex) { expandBuffers(); final int newState = size; final int start = activePath[activePathIndex]; final int len = nextArcOffset[activePathIndex] - start; System.arraycopy(serialized, start, serialized, newState, len); size += len; return newState...
java
public void createLayout(final Sbgn sbgn, boolean doLayout) { viewToLayout = new HashMap(); glyphToVNode = new HashMap(); idToGLyph = new HashMap(); idToCompartmentGlyphs = new HashMap(); portIDToOwnerGlyph = new HashMap(); layoutToView = new HashMap(); idToAr...
python
def _notify_single_step(self, event): """ Notify breakpoints of a single step exception event. @type event: L{ExceptionEvent} @param event: Single step exception event. @rtype: bool @return: C{True} to call the user-defined handle, C{False} otherwise. """ ...
python
def write_name (self, url_data): """Write url_data.name.""" args = (self.part("name"), cgi.escape(url_data.name)) self.writeln(u"<tr><td>%s</td><td>`%s'</td></tr>" % args)
python
def avail_platforms(): ''' Return which platforms are available CLI Example: .. code-block:: bash salt myminion genesis.avail_platforms ''' ret = {} for platform in CMD_MAP: ret[platform] = True for cmd in CMD_MAP[platform]: if not salt.utils.path.which...
java
public static String buildQueryString(boolean distinct, String[] tables, String[] columns, String[] columnsAs, String where, String groupBy, String having, String orderBy, String limit) { if (isEmpty(groupBy) && !isEmpty(having)) { throw new IllegalArgumentException( "HAVING clauses are only permitted w...
python
def search(self, id_list: Iterable, negated_classes: Iterable, limit: Optional[int], method: Optional) -> List[SimResult]: """ Given an input list of classes, searches for similar lists of classes and provides a ranked list of matches ...
java
@Override protected PlainDate getDate0(int year) { int month = this.getMonthValue(); int lastDay = GregorianMath.getLengthOfMonth(year, month); int lastW = GregorianMath.getDayOfWeek(year, month, lastDay); int delta = (lastW - this.dayOfWeek); if (delta < 0) { d...
python
def get_instance(self, node, *args, **kwargs): """ get plugin instance from config node *NOTE* returns an uninitialized instance if one isn't there *NOTE* instantiated plugins without names remain anonymous FIXME - why would instantiate() even process them """ ...
java
private CmsNewResourceInfo createNavigationLevelTypeInfo() throws CmsException { String name = CmsResourceTypeFolder.getStaticTypeName(); Locale locale = getWorkplaceLocale(); String subtitle = Messages.get().getBundle(getWorkplaceLocale()).key(Messages.GUI_NAVIGATION_LEVEL_SUBTITLE_0); ...
java
public java.lang.String getGet() { java.lang.Object ref = ""; if (patternCase_ == 2) { ref = pattern_; } if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.la...
java
protected void checkMapSize() { if ((map instanceof EmbeddedSlotMap) && map.size() >= LARGE_HASH_SIZE) { SlotMap newMap = new HashSlotMap(); for (Slot s : map) { newMap.addSlot(s); } map = newMap; } }
python
def _init_compiled(cls, dialect, connection, dbapi_connection, compiled, parameters): """Initialize execution context for a Compiled construct.""" self = cls.__new__(cls) self.root_connection = connection self._dbapi_connection = dbapi_connection self.dial...
python
def get_pos_kw(self, token): """Return then the number of positional parameters and represented by the attr field of token""" # Low byte indicates number of positional paramters, # high byte number of keyword parameters args_pos = token.attr & 0xff args_kw = (token.attr >...
java
@Override public byte[] retrieveBytes(File impFi) { if ( resourceLocator != null ) { // does only return a result if a transpiler is registered byte[] bytes = resourceLocator.retrieveBytes(impFi); if ( bytes != null ) return bytes; } return...
java
public static Class<?> getBoxedClass(Class<?> type) { if (type == boolean.class) { return Boolean.class; } else if (type == char.class) { return Character.class; } else if (type == byte.class) { return Byte.class; } else if (type == short.class) { ...
java
@Override public final Set<IPersonAttributes> getPeopleWithMultivaluedAttributes( Map<String, List<Object>> query) { Validate.notNull(query, "query may not be null."); // Generate the query to pass to the subclass final LocalAccountQuery queryBuilder = this.generateQuery(query);...
java
public Observable<Page<FileServerInner>> listByResourceGroupNextAsync(final String nextPageLink) { return listByResourceGroupNextWithServiceResponseAsync(nextPageLink) .map(new Func1<ServiceResponse<Page<FileServerInner>>, Page<FileServerInner>>() { @Override public P...
python
def requestUnOrdered(self, key: str): """ Record the time at which request ordering started. """ now = time.perf_counter() if self.acc_monitor: self.acc_monitor.update_time(now) self.acc_monitor.request_received(key) self.requestTracker.start(key, ...
python
def urlsplit(url): """Split an arbitrary url into protocol, host, rest The standard urlsplit does not want to provide 'netloc' for arbitrary protocols, this works around that. :param url: The url to split into component parts """ proto, rest = url.split(':', 1) host = '' if rest[:2] ==...
java
protected Response findAppropriateResponse(Attack attack) { Rule triggeringRule = attack.getRule(); SearchCriteria criteria = new SearchCriteria(). setUser(attack.getUser()). setRule(triggeringRule). setDetectionSystemIds(appSensorServer.getConfiguration().getRelatedDetectionSystems(attack.getDetection...
python
def _get_cache_contents(self): """ Return list of commit hash directories in the cache (containing wheels or not), sorted by decreasing timestamp """ if not os.path.isdir(self._path): return [] def sort_key(name): path, stamp = self._get_cache_dir...
python
def confidential_interval(x, alpha=0.98): """ Return a numpy array of column confidential interval Parameters ---------- x : ndarray A numpy array instance alpha : float Alpha value of confidential interval Returns ------- ndarray A 1 x n numpy array which i...
java
private void backpropagate() { for (int l = net.length; --l > 0;) { backpropagate(net[l], net[l - 1]); } }
python
def first_from_generator(generator): """Pull the first value from a generator and return it, closing the generator :param generator: A generator, this will be mapped onto a list and the first item extracted. :return: None if there are no items, or the first item otherwise. :internal: ...
python
def geocode_location(location, sensor=False, api_key=None): """Converts a human-readable location to lat-lng. Returns a dict with lat and lng keys. keyword arguments: location -- A human-readable location, e.g 'London, England' sensor -- Boolean flag denoting if the location came from a device u...
java
public static Endpoint create(final BandwidthClient client, final String domainId, final Map<String, Object>params) throws AppPlatformException, ParseException, Exception { assert (client!= null && params != null); final String endpointsUri = String.format(client.getUserResourceUri(BandwidthConstants.EN...
python
def check_style(value): """ Validate a logging format style. :param value: The logging format style to validate (any value). :returns: The logging format character (a string of one character). :raises: :exc:`~exceptions.ValueError` when the given style isn't supported. On Python 3.2+ this func...
java
void addCombinableExecutionGraph(DStreamExecutionGraph combinableExecutionGraph){ if (this.combinableExecutionGraphs == null){ this.combinableExecutionGraphs = new ArrayList<>(); } this.combinableExecutionGraphs.add(combinableExecutionGraph); }
python
def install_metaboard( replace_existing=False, ): """install metaboard. http://metalab.at/wiki/Metaboard """ metaboard = AutoBunch() metaboard.name = 'Metaboard' metaboard.upload.protocol = 'usbasp' metaboard.upload.maximum_size = '14336' metaboard.upload.speed = '19200' meta...