language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public boolean pushResponsePayload(ResponsePayload responsePayload) { if (payloads.containsKey(responsePayload.getSerialId())) { payloads.put(responsePayload.getSerialId(), responsePayload); return true; } return false; }
python
def add_proxy(self, proxy): """Add a valid proxy into pool You must call `add_proxy` method to add a proxy into pool instead of directly operate the `proxies` variable. """ protocol = proxy.protocol addr = proxy.addr if addr in self.proxies: self.prox...
java
synchronized ListenableFuture<?> moveQuery(QueryId queryId, MemoryPool targetMemoryPool) { long originalReserved = getQueryMemoryReservation(queryId); long originalRevocableReserved = getQueryRevocableMemoryReservation(queryId); // Get the tags before we call free() as that would remove the ...
java
protected void bcsPreSerializationHook(ObjectOutputStream oos) throws IOException { super.bcsPreSerializationHook(oos); // serialize services synchronized (services) { oos.writeInt(serializable); for (Iterator iter = services.entrySet().iterator(); iter.hasNext();) { Entry entry = (Entry) iter.ne...
java
private void checkPlaceholderVisibility(I_CmsDropTarget target) { if (target instanceof I_CmsDropContainer) { I_CmsDropContainer container = (I_CmsDropContainer)target; container.setPlaceholderVisibility( (container != m_initialDropTarget) || ((m_curr...
python
def get_summary_stats(items, attr): """ Returns a dictionary of aggregated statistics for 'items' filtered by "attr'. For example, it will aggregate statistics for a host across all the playbook runs it has been a member of, with the following structure: data[host.id] = { 'ok': 4 ...
python
def designPrimers(p3_args, input_log=None, output_log=None, err_log=None): ''' Return the raw primer3_core output for the provided primer3 args. Returns an ordered dict of the boulderIO-format primer3 output file ''' sp = subprocess.Popen([pjoin(PRIMER3_HOME, 'primer3_core')], ...
java
private void primitive(int typeCode, Object obj) { switch (typeCode) { case T_BOOLEAN: dest.emit(LDC, ((Boolean) obj).booleanValue()? 1 : 0); break; case T_CHAR: dest.emit(LDC, ((Character) obj).charValue()); break; case T_BYTE: cas...
python
def export_widgets(self_or_cls, obj, filename, fmt=None, template=None, json=False, json_path='', **kwargs): """ Render and export object as a widget to a static HTML file. Allows supplying a custom template formatting string with fields to interpolate 'js', 'css' ...
java
public AlertConditionCache alertConditions(long policyId) { AlertConditionCache cache = conditions.get(policyId); if(cache == null) conditions.put(policyId, cache = new AlertConditionCache(policyId)); return cache; }
python
def ppo_original_world_model_stochastic_discrete(): """Atari parameters with stochastic discrete world model as policy.""" hparams = ppo_original_params() hparams.policy_network = "next_frame_basic_stochastic_discrete" hparams_keys = hparams.values().keys() video_hparams = basic_stochastic.next_frame_basic_st...
python
def setAutoscaledNodeTypes(self, nodeTypes): """ Set node types, shapes and spot bids. Preemptable nodes will have the form "type:spotBid". :param nodeTypes: A list of node types """ self._spotBidsMap = {} self.nodeShapes = [] self.nodeTypes = [] for nodeT...
java
public String setClassification(String classificationType) { Metadata metadata = new Metadata().add(Metadata.CLASSIFICATION_KEY, classificationType); Metadata classification = null; try { classification = this.createMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY, "enterprise", metada...
java
@Override public UpdateIndexingConfigurationResult updateIndexingConfiguration(UpdateIndexingConfigurationRequest request) { request = beforeClientExecution(request); return executeUpdateIndexingConfiguration(request); }
python
def kline_echarts(self, code=None): def kline_formater(param): return param.name + ':' + vars(param) """plot the market_data""" if code is None: path_name = '.' + os.sep + 'QA_' + self.type + \ '_codepackage_' + self.if_fq + '.html' kline = K...
python
def lock(self, back=None, remote=None): ''' ``remote`` can either be a dictionary containing repo configuration information, or a pattern. If the latter, then remotes for which the URL matches the pattern will be locked. ''' back = self.backends(back) locked = [] ...
java
public void setFragments(List<XmlFragment> fragments) { assertNotNull(fragments); this.fragments.clear(); for (XmlFragment fragment : fragments) addFragment(fragment); }
java
public static <T> Collector<T, ?, OptionalLong> andingLong(ToLongFunction<T> mapper) { return new CancellableCollectorImpl<>(PrimitiveBox::new, (acc, t) -> { if (!acc.b) { acc.l = mapper.applyAsLong(t); acc.b = true; } else { acc.l &=...
python
def transform_dataframe(self, dataframe): """ Use matplotlib to compute boxplot statistics on e.g. timeseries data. """ grouping = self.get_grouping(dataframe) group_field = self.get_group_field() header_fields = self.get_header_fields() if "series" in grouping: ...
java
public static JavaRDD<DataSet> fromContinuousLabeledPoint(JavaRDD<LabeledPoint> data, boolean preCache) { if (preCache && !data.getStorageLevel().useMemory()) { data.cache(); } return data.map(new Function<LabeledPoint, DataSet>() { @Override public DataSet ca...
java
public List<String> replaceAbstractClasses(List<String> lines) { List<String> result = new LinkedList<String>(); for (int i = 0; i < lines.size(); i++) { result.add(removeAbstract(lines.get(i))); } return result; }
java
public Object getMergePolicy(String className) { if (className == null) { throw new InvalidConfigurationException("Class name is mandatory!"); } try { return policyProvider.getMergePolicy(className); } catch (InvalidConfigurationException e) { return g...
java
public ProtectedBranch protectBranch(Integer projectIdOrPath, String branchName) throws GitLabApiException { return protectBranch(projectIdOrPath, branchName, AccessLevel.MAINTAINER, AccessLevel.MAINTAINER); }
python
def get_permissions_for_registration(self): """ Utilised by Wagtail's 'register_permissions' hook to allow permissions for a model to be assigned to groups in settings. This is only required if the model isn't a Page model, and isn't registered as a Snippet """ from wagta...
java
private <T> void addBinding(Class<T> type, BindingAmp<T> binding) { synchronized (_bindingSetMap) { BindingSet<T> set = (BindingSet) _bindingSetMap.get(type); if (set == null) { set = new BindingSet<>(type); _bindingSetMap.put(type, set); } set.addBinding(binding); } ...
java
private Map<Object, Object> lazyProperties() { if (properties == null) { properties = new Hashtable<Object, Object>(); } return properties; }
java
public static boolean del(File file) throws IORuntimeException { if (file == null || false == file.exists()) { // 如果文件不存在或已被删除,此处返回true表示删除成功 return true; } if (file.isDirectory()) { // 清空目录下所有文件和目录 boolean isOk = clean(file); if (false == isOk) { return false; } } // 删除文...
python
def version(self): """Return version of the TR DWE.""" res = self.client.service.Version() return '.'.join([ustr(x) for x in res[0]])
java
public Map<String,Object> handleUpdateFilterMap(Map<String,Object> propFilter) { if (propFilter != null) { Object bookmark = propFilter.get(ADD_BOOKMARK); if (bookmark != null) { if (CLEAR_BOOKMARKS.equals(bookmark)) { ...
python
def _set_ospf_route_map(self, v, load=False): """ Setter method for ospf_route_map, mapped from YANG variable /routing_system/router/isis/router_isis_cmds_holder/address_family/ipv6/af_ipv6_unicast/af_ipv6_attributes/af_common_attributes/redistribute/ospf/ospf_route_map (rmap-type) If this variable is read-...
java
private List<String> readLinkExcludes(CmsObject cms) { List<String> linkExcludes = new ArrayList<String>(); try { // get the link exclude file String filePath = OpenCms.getSystemInfo().getConfigFilePath(cms, LINK_EXCLUDE_DEFINIFITON_FILE); CmsResource res = cms.read...
java
@Deprecated public static String jsonEncodedStringFor(Value value) { try { if (value.getType() != PropertyType.BINARY) { return value.getString(); } // Encode the binary value in Base64 ... InputStream stream = value.getBinary().getStream(); ...
java
public ThriftServerDef build() { checkState(niftyProcessorFactory != null || thriftProcessorFactory != null, "Processor not defined!"); checkState(niftyProcessorFactory == null || thriftProcessorFactory == null, "TProcessors will be automatically adapted to Nift...
java
protected void stop() throws Exception { this.logger.debug("Stopping application"); this.stopLock.lock(); try { for (ConfigurableApplicationContext context : this.rootContexts) { context.close(); this.rootContexts.remove(context); } cleanupCaches(); if (this.forceReferenceCleanup) { forceR...
java
public void addMixin(final FedoraResource resource, final Resource mixinResource, final Map<String,String> namespaces) throws RepositoryException { final Node node = getJcrNode(resource); final Session session = node.getSession(); fi...
java
public SubscriptionMatchResult match(String theCriteria, IBaseResource theResource, ResourceIndexedSearchParams theSearchParams) { RuntimeResourceDefinition resourceDefinition; if (theResource == null) { resourceDefinition = UrlUtil.parseUrlResourceType(myFhirContext, theCriteria); } else { resourceDefiniti...
python
def get_room_messages(self, room_id, token, direction, limit=10, to=None): """Perform GET /rooms/{roomId}/messages. Args: room_id (str): The room's id. token (str): The token to start returning events from. direction (str): The direction to return events from. One o...
python
def update_context(app, pagename, templatename, context, doctree): """ Remove sphinx-tabs CSS and JS asset files if not used in a page """ if doctree is None: return visitor = _FindTabsDirectiveVisitor(doctree) doctree.walk(visitor) if not visitor.found_tabs_directive: paths = [posix...
java
public void update ( byte[] input, int offset, int len ) { if ( log.isTraceEnabled() ) { log.trace("update: " + this.updates + " " + offset + ":" + len); log.trace(Hexdump.toHexString(input, offset, Math.min(len, 256))); } if ( len == 0 ) { return; /* CRITICAL...
python
def callsign(msg): """Aircraft callsign Args: msg (string): 28 bytes hexadecimal message string Returns: string: callsign """ if common.typecode(msg) < 1 or common.typecode(msg) > 4: raise RuntimeError("%s: Not a identification message" % msg) chars = '#ABCDEFGHIJKLMN...
python
def exists(zpool): ''' Check if a ZFS storage pool is active zpool : string Name of storage pool CLI Example: .. code-block:: bash salt '*' zpool.exists myzpool ''' # list for zpool # NOTE: retcode > 0 if zpool does not exists res = __salt__['cmd.run_all']( ...
java
public Rcli<CLIENT> clientAs(String apiVersion, ServletRequest req) throws CadiException { Rcli<CLIENT> cl = client(apiVersion); return cl.forUser(transferSS(((HttpServletRequest)req).getUserPrincipal())); }
java
static int[] unwrappingGetItems(final PairTable table, final int numPairs) { if (numPairs < 1) { return null; } final int[] slotsArr = table.slotsArr; final int tableSize = 1 << table.lgSizeInts; final int[] result = new int[numPairs]; int i = 0; int l = 0; int r = numPairs - 1; // Spec...
python
def indent(indent_str=None): """ An example indentation ruleset. """ def indentation_rule(): inst = Indentator(indent_str) return {'layout_handlers': { Indent: inst.layout_handler_indent, Dedent: inst.layout_handler_dedent, Newline: inst.layout_handle...
java
public static byte[] convertUtf16UnitsToUtf8(String text) { byte[] data = new byte[4*text.length()]; int limit = 0; for (int i = 0; i < text.length(); i++) { char c = text.charAt(i); limit += IonUTF8.convertToUTF8Bytes(c, data, limit, ...
java
public <T> T toOnlyElement(Function<? super Cursor, T> singleRowTransform, T defaultValue) { if (moveToFirst()) { return toOnlyElement(singleRowTransform); } else { close(); return defaultValue; } }
java
public RequestHeader withPrincipal(Principal principal) { return new RequestHeader(method, uri, protocol, acceptedResponseProtocols, Optional.ofNullable(principal), headers, lowercaseHeaders); }
java
public static NullPointerException newNullPointerException(Throwable cause, String message, Object... args) { return (NullPointerException) new NullPointerException(format(message, args)).initCause(cause); }
java
public StringProcessChain replacIgnoreCase(final String target, final String replacement) { StringBuilder result = new StringBuilder(); String temp = source; int indexOfIgnoreCase = 0; while (true) { indexOfIgnoreCase = StringUtils.indexOfIgnoreCase(temp, target); if (indexOfIgnoreCase == S...
python
def _list_deployment_instances(awsclient, deployment_id): """list deployment instances. :param awsclient: :param deployment_id: """ client_codedeploy = awsclient.get_client('codedeploy') instances = [] next_token = None # TODO refactor generic exhaust_function from this while True...
python
def load_configuration(self) -> None: """ Read the configuration from a configuration file """ config_file = self.default_config_file if self.config_file: config_file = self.config_file self.config = ConfigParser() self.config.read(config_file)
python
def dump(obj, fp, **kwargs): """wrapper for :py:func:`json.dump`""" kwargs['default'] = serialize return json.dump(obj, fp, **kwargs)
python
def luhn(n): """Validate that a string made of numeric characters verify Luhn test. Used by siret validator. from http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers#Python https://en.wikipedia.org/wiki/Luhn_algorithm """ r = [int(ch) for ch in str(n)][::-1] return (sum(r[0::2]...
java
private boolean canBeRetrievedFromQueueBuffer(ReceiveMessageRequest rq) { return !hasRequestedQueueAttributes(rq) && requestedMessageAttributesAreCompatible(rq) && isBufferingEnabled() && (rq.getVisibilityTimeout() == null); }
java
public static void isEqual (final int nValue, final int nExpectedValue, @Nonnull final Supplier <? extends String> aName) { if (isEnabled ()) if (nValue != nExpectedValue) throw new IllegalArgumentException ("The value of '" + ...
python
def product(self, *products): r""" When search is called, it will limit the results to items in a Product. :param product: items passed in will be turned into a list :returns: :class:`Search` """ for product in products: self._product.append(produ...
java
public void logError(String moduleName, String beanName, String methodName) { Tr.error(tc, ivError.getMessageId(), new Object[] { beanName, moduleName, methodName, ivField }); }
java
private Map<String,Function<HttpRequestContext, String>> createSubstitutionMap(String[] permissions, AbstractMethod am) { Map<String, Function<HttpRequestContext, String>> map = Maps.newLinkedHashMap(); for (String permission : permissions) { Matcher matcher = SUBSTITUTION_MATCHER.matcher(p...
java
public void setXCENT(Integer newXCENT) { Integer oldXCENT = xcent; xcent = newXCENT; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.GPARC__XCENT, oldXCENT, xcent)); }
java
public String getInitialCommand(boolean bIncludeAppletCommands) { String strCommand = Constants.BLANK; if (bIncludeAppletCommands) { if (this.getProperty(Params.APPLET) != null) strCommand = Util.addURLParam(strCommand, Params.APPLET, this.getProperty(Params.APPLET)); else if (this.ge...
java
public JMProgressiveManager<T, R> registerCountChangeListener(Consumer<Number> countChangeListener) { return registerListener(progressiveCount, countChangeListener); }
python
def get_bottom(depths, des_mask, asc_mask): '''Get boolean mask of regions in depths the animal is at the bottom Args ---- des_mask: ndarray Boolean mask of descents in the depth data asc_mask: ndarray Boolean mask of ascents in the depth data Returns ------- BOTTOM: nd...
python
def write(self, chunk): """Writes the given chunk to the output buffer. Checks for curl in the user-agent and if set, provides indented output if returning JSON. To write the output to the network, use the flush() method below. If the given chunk is a dictionary, we write it as JSON an...
java
public Observable<Void> beginValidateMoveResourcesAsync(String sourceResourceGroupName, ResourcesMoveInfo parameters) { return beginValidateMoveResourcesWithServiceResponseAsync(sourceResourceGroupName, parameters).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call...
java
public static void isFalse(Boolean condition, Supplier<String> message) { if (isNotFalse(condition)) { throw new IllegalArgumentException(message.get()); } }
python
def pressed_keys(self): """An array containing all detected keys that are pressed from the initalized list-of-lists passed in during creation""" # make a list of all the keys that are detected pressed = [] # set all pins pins to be inputs w/pullups for pin in self.row_pi...
python
def render_registered(url_id, remote_info): """ Render template file for the registered user, which has some of the values prefilled. Args: url_id (str): Seeder URL id. remote_info (dict): Informations read from Seeder. Returns: str: Template filled with data. """ r...
python
def _fire_bundle_event(self, kind): # type: (int) -> None """ Fires a bundle event of the given kind :param kind: Kind of event """ self.__framework._dispatcher.fire_bundle_event(BundleEvent(kind, self))
java
public static double angle(double[] v1, double[] v2) { final int mindim = (v1.length <= v2.length) ? v1.length : v2.length; // Essentially, we want to compute this: // v1.transposeTimes(v2) / (v1.euclideanLength() * v2.euclideanLength()); // We can just compute all three in parallel. double s = 0, e...
python
def close(self): """ Close this file and commit it to its permanent location. @return: a Deferred which fires when the file has been moved (and backed up to tertiary storage, if necessary). """ now = time.time() try: file.close(self) _mkdi...
python
def skos_symmetric_mappings(rdf, related=True): """Ensure that the symmetric mapping properties (skos:relatedMatch, skos:closeMatch and skos:exactMatch) are stated in both directions (S44). :param bool related: Add the skos:related super-property for all skos:relatedMatch relations (S41). """ ...
java
public static Coordinate createCoordinate(Attributes attributes) throws NumberFormatException { // Associate a latitude and a longitude to the point double lat; double lon; try { lat = Double.parseDouble(attributes.getValue(GPXTags.LAT)); } catch (NumberFormatExceptio...
python
def saveShp(self, target): """Save an shp file.""" if not hasattr(target, "write"): target = os.path.splitext(target)[0] + '.shp' if not self.shapeType: self.shapeType = self._shapes[0].shapeType self.shp = self.__getFileObj(target) self.__shapefile...
python
def track_event(self, name, properties=None, measurements=None): """ Send information about a single event that has occurred in the context of the application. Args: name (str). the data to associate to this event.\n properties (dict). the set of custom properties the client wan...
java
public boolean subclassOf(ClassDoc cd) { return tsym.isSubClass(((ClassDocImpl)cd).tsym, env.types); }
python
def _get_submission_model(uuid, read_replica=False): """ Helper to retrieve a given Submission object from the database. Helper is needed to centralize logic that fixes EDUCATOR-1090, because uuids are stored both with and without hyphens. """ submission_qs = Submission.objects if read_replica: ...
java
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) { Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888); Canvas canvas = new Canvas(output); final int color = 0xff424242; final Paint paint = new Paint(); final Rect...
java
public static dnsview[] get_filtered(nitro_service service, String filter) throws Exception{ dnsview obj = new dnsview(); options option = new options(); option.set_filter(filter); dnsview[] response = (dnsview[]) obj.getfiltered(service, option); return response; }
python
def _prepare_batch_request(self): """Prepares headers and body for a batch request. :rtype: tuple (dict, str) :returns: The pair of headers and body of the batch request to be sent. :raises: :class:`ValueError` if no requests have been deferred. """ if len(self._requests...
python
def reactToMessage(self, message_id, reaction): """ Reacts to a message, or removes reaction :param message_id: :ref:`Message ID <intro_message_ids>` to react to :param reaction: Reaction emoji to use, if None removes reaction :type reaction: models.MessageReaction or None ...
java
private ServerEventHandler createServerEventHandler( SFSEventType type, Class<?> clazz) { try { return (ServerEventHandler) ReflectClassUtil.newInstance( clazz, BaseAppContext.class, context); } catch (ExtensionException e) { getLogger().error("Error when create server event handlers", e); ...
java
public static File toJsonFile(String jsonString, File returnJsonFile) { try { jsonMapper.writeValue(returnJsonFile, jsonString); return returnJsonFile; } catch (Exception e) { return JMExceptionManager.handleExceptionAndReturnNull(log, e, "toJsonFi...
python
def process_form(self, instance, field, form, empty_marker=None, emptyReturnsMarker=False): """A typed in value takes precedence over a selected value. """ name = field.getName() otherName = "%s_other" % name value = form.get(otherName, empty_marker) ...
java
public static void sync(long sourceFileTimeStamp, File generatedSourceFile, File classFile, String className, boolean keepgenerated, boolean keepGeneratedclassfiles) { if(com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable(Level.FINEST)){ logger.logp(Level.FINEST, CLASS_NAME, "sy...
java
private static <T extends Comparable<? super T>> Observable<T> minMax( Observable<T> source, final int flag) { return minMax(source, OnSubscribeMinMax.COMPARABLE_MIN, flag); }
java
protected String resolveKey(String alias) { List<String> possibleKeys = aliases.get(alias); for (String key : possibleKeys) { if (resolver.containsProperty(key)) { return key; } } return null; }
java
@Nonnull public static IUserAgent getUserAgent (@Nonnull final HttpServletRequest aHttpRequest) { IUserAgent aUserAgent = (IUserAgent) aHttpRequest.getAttribute (IUserAgent.class.getName ()); if (aUserAgent == null) { // Extract HTTP header from request final String sUserAgent = getHttpUserA...
java
public int nextInt(int bound) { if (bound <= 0) throw new IllegalArgumentException(BAD_BOUND); int r = mix32(nextSeed()); int m = bound - 1; if ((bound & m) == 0) // power of two r &= m; else { // reject over-represented candidates for (int u =...
python
def get_map_location(target_device, fallback_device='cpu'): """Determine the location to map loaded data (e.g., weights) for a given target device (e.g. 'cuda'). """ map_location = torch.device(target_device) # The user wants to use CUDA but there is no CUDA device # available, thus fall back t...
python
def _do_callbacks(self): """Perform the callbacks.""" self._done = False while self._callbacks and not self._cancelled: cb, eb, cb_args, cb_kwargs, eb_args, eb_kwargs = self._callbacks.pop() if cb and not self._exception: try: self._re...
java
public static ResourceRecordSet<CNAMEData> cname(String name, String cname) { return new CNAMEBuilder().name(name).add(cname).build(); }
python
async def set(self, key, value, *, flags=None): """Sets the key to the given value. Parameters: key (str): Key to set value (Payload): Value to set, It will be encoded by flags flags (int): Flags to set with value Returns: bool: ``True`` on succes...
python
def handle(self, *arguments, **options): """ Parses arguments and options, runs validate_<action> for each action named by self.get_actions(), then runs handle_<action> for each action named by self.get_actions(). """ self.arguments = arguments self.optio...
python
def _calc_outliers_bounds(self, data, method, coeff, window): """ Calculate the lower and higher bound for outlier detection. Parameters ---------- data : pd.DataFrame() Input dataframe. method : str Method to use for calculating the...
java
public EndpointManager<TcpIpConnection> getEndpointManager(EndpointQualifier qualifier) { EndpointManager<TcpIpConnection> mgr = endpointManagers.get(qualifier); if (mgr == null) { logger.finest("An endpoint manager for qualifier " + qualifier + " was never registered."); } ...
python
def convert_square(node, **kwargs): """Map MXNet's square operator attributes to onnx's Pow operator and return the created node. """ name, input_nodes, _ = get_inputs(node, kwargs) initializer = kwargs["initializer"] data_type = onnx.mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype('int64')] power...
java
public com.google.api.ads.admanager.axis.v201811.Money getNetCost() { return netCost; }
java
protected void addWord(Stack<Word> result, String text, int start, int len){ Word word = getWord(text, start, len); if(word != null){ result.push(word); } }
python
def import_plugin(name, superclasses=None): """Import name as a module and return a list of all classes defined in that module. superclasses should be a tuple of valid superclasses to import, this defaults to (Plugin,). """ plugin_fqname = "sos.plugins.%s" % name if not superclasses: sup...
python
def _concatenate_virtual_arrays(arrs, cols=None, scaling=None): """Return a virtual concatenate of several NumPy arrays.""" return None if not len(arrs) else ConcatenatedArrays(arrs, cols, scaling=scaling)