language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def create_training_example(self, environment_id, collection_id, query_id, document_id=None, cross_reference=None, relevance=Non...
java
@Override public Map<String, List<String>> get(URI uri, Map<String, List<String>> requestHeaders) throws IOException { clearExpired(new Date()); ArrayList<String> cookies = new ArrayList<String>(); for (Cookie cookie : getCookies(uri)) { cookies.add(cookie.getName() + "=" + cookie.getValue()); } return si...
java
public String[][] getPopupMap() { String string[][] = { {RunProcessInField.LOCAL, "Run locally"}, {RunProcessInField.LOCAL_PROCESS, "Local process"}, {RunProcessInField.REMOTE_PROCESS, "Remote process"}, }; return string; }
java
@Indexable(type = IndexableType.REINDEX) @Override public CommerceNotificationTemplate addCommerceNotificationTemplate( CommerceNotificationTemplate commerceNotificationTemplate) { commerceNotificationTemplate.setNew(true); return commerceNotificationTemplatePersistence.update(commerceNotificationTemplate); }
java
@Override public Object proceed() throws Exception { Object rc = null; //if there are more interceptors left in the chain, call the next one if (nextInterceptor < interceptors.size()) { rc = invokeNextInterceptor(); } else { //otherwise call proceed o...
python
def convex_conj(self): """The convex conjugate functional of the group L1-norm.""" conj_exp = conj_exponent(self.pointwise_norm.exponent) return IndicatorGroupL1UnitBall(self.domain, exponent=conj_exp)
java
public TLSARecord getTLSARecord(URL url) { String recordValue; int port = url.getPort(); if (port == -1) { port = url.getDefaultPort(); } String tlsaRecordName = String.format("_%s._tcp.%s", port, DNSUtil.ensureDot(url.getHost())); try { recordVa...
java
private boolean isAnomaly(Instance instance, ActiveRule rule) { //AMRUles is equipped with anomaly detection. If on, compute the anomaly value. boolean isAnomaly = false; if (this.noAnomalyDetection == false){ if (rule.getInstancesSeen() >= this.anomalyNumInstThreshold) { isAnomaly = rule.isAnomaly(in...
java
@Nullable private static File _getResourceSource (final String resource, final ClassLoader loader) { if (resource != null) { URL url; if (loader != null) { url = loader.getResource (resource); } else { url = ClassLoader.getSystemResource (resource); ...
java
public Observable<VirtualNetworkRuleInner> createOrUpdateAsync(String resourceGroupName, String accountName, String virtualNetworkRuleName, CreateOrUpdateVirtualNetworkRuleParameters parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, accountName, virtualNetworkRuleName, parameters).m...
python
def getOSDesc(interface, ext_list): """ Return an OS description header. interface (int) Related interface number. ext_list (list of OSExtCompatDesc or OSExtPropDesc) List of instances of extended descriptors. """ try: ext_type, = {type(x) for x in ext_list} except Va...
python
def _process_phenstatement(self, limit): """ The phenstatements are the genotype-to-phenotype associations, in the context of an environment. These are also curated to a publication. So we make oban associations, adding the pubs as a source. We additionally add the internal key ...
java
public static Integer[] createAndInitializeArray(int size, Integer start) { Integer[] result = new Integer[size]; for (int i = 0; i < result.length; i++) { result[i] = start++; } return result; }
python
def sample_bitstrings(self, n_samples): """ Sample bitstrings from the distribution defined by the wavefunction. :param n_samples: The number of bitstrings to sample :return: An array of shape (n_samples, n_qubits) """ possible_bitstrings = np.array(list(itertools.produc...
java
public <X extends Exception> boolean replaceAllIf(Try.Predicate<? super K, X> predicate, Collection<?> oldValues, E newValue) throws X { boolean modified = false; for (Map.Entry<K, V> entry : this.valueMap.entrySet()) { if (predicate.test(entry.getKey())) { if (entry.ge...
java
@Override public int compare(JTAResource o1, JTAResource o2) { if (tc.isEntryEnabled()) Tr.entry(tc, "compare", new Object[] { o1, o2, this }); int result = 0; int p1 = o1.getPriority(); int p2 = o2.getPriority(); if (p1 < p2) result = 1; else ...
java
public BlockMeta getBlockMeta(long blockId) throws BlockDoesNotExistException { BlockMeta blockMeta = mBlockIdToBlockMap.get(blockId); if (blockMeta == null) { throw new BlockDoesNotExistException(ExceptionMessage.BLOCK_META_NOT_FOUND, blockId); } return blockMeta; }
java
protected void arrangePreparedAccessContext(LaJobRuntime runtime) { if (accessContextArranger == null) { return; } final AccessContextResource resource = createAccessContextResource(runtime); final AccessContext context = accessContextArranger.arrangePreparedAccessContext(res...
java
public void copyCategories(CmsObject cms, CmsResource fromResource, String toResourceSitePath) throws CmsException { List<CmsCategory> categories = readResourceCategories(cms, fromResource); for (CmsCategory category : categories) { addResourceToCategory(cms, toResourceSitePath, category); ...
java
@Override public String asString() { ByteArrayOutputStream result = new ByteArrayOutputStream(getIntContentLength(this.response)); saveTo(result); return result.toString(); }
java
public static Map createHeaderMap(PageContext pContext) { final HttpServletRequest request = (HttpServletRequest) pContext.getRequest(); return new EnumeratedMap() { public Enumeration enumerateKeys() { return request.getHeaderNames();...
python
def edges(self, source=None, relation=None, target=None): """ Return edges filtered by their *source*, *relation*, or *target*. Edges don't include terminal triples (node types or attributes). """ edgematch = lambda e: ( (source is None or source == e.source) and ...
java
public void setOutputFile (final File value) { if (value != null && !value.isAbsolute ()) { throw new IllegalArgumentException ("path is not absolute: " + value); } this.outputFile = value; }
java
public void serviceName_account_userPrincipalName_PUT(String serviceName, String userPrincipalName, OvhAccount body) throws IOException { String qPath = "/msServices/{serviceName}/account/{userPrincipalName}"; StringBuilder sb = path(qPath, serviceName, userPrincipalName); exec(qPath, "PUT", sb.toString(), body);...
java
public boolean marketplace_removeListing(Long listingId, CharSequence status) throws FacebookException, IOException { assert MARKETPLACE_STATUS_DEFAULT.equals(status) || MARKETPLACE_STATUS_SUCCESS.equals(status) || MARKETPLACE_STATUS_NOT_SUCCESS.equals(status) : "Invalid status: " + status; T result ...
python
def geometric_partitions(iterable, floor=1, ceiling=32768): ''' Partition an iterable into chunks. Returns an iterator over partitions. ''' partition_size = floor run_length = multiprocessing.cpu_count() run_count = 0 try: while True: #print("partition_size ="...
python
def stage_pywbem_args(self, method, **kwargs): """ Set requst method and all args. Normally called before the cmd is executed to record request parameters """ # pylint: disable=attribute-defined-outside-init self._pywbem_method = method self._pywbem_args =...
python
def star(self, login, repo): """Star to login/repo :param str login: (required), owner of the repo :param str repo: (required), name of the repo :return: bool """ resp = False if login and repo: url = self._build_url('user', 'starred', login, repo) ...
java
private static void weaveDNAStrands(LinkedList<DNASegment> segments, int firstJulianDay, HashMap<Integer, DNAStrand> strands, int top, int bottom, int[] dayXs) { // First, get rid of any colors that ended up with no segments Iterator<DNAStrand> strandIterator = st...
python
def geoid(self): """"Return first child of the column, or self that is marked as a geographic identifier""" if self.valuetype_class.is_geoid(): return self for c in self.table.columns: if c.parent == self.name and c.valuetype_class.is_geoid(): return c
java
List<PartitionInstance> getAbsent() { List<PartitionInstance> absentPartitions = new ArrayList<>(); for (Map.Entry<Integer, List<PartitionInstance>> e : nodeIndexToHostedPartitions.entrySet()) { if (e.getKey() < 0) { absentPartitions.addAll(e.getValue()); } } return absentPartitions;...
java
public static void parseLongestText(String text, AhoCorasickDoubleArrayTrie.IHit<CoreDictionary.Attribute> processor) { if (trie != null) { final int[] lengthArray = new int[text.length()]; final CoreDictionary.Attribute[] attributeArray = new CoreDictionary.Attribute[text.le...
python
def interpoled_resampling(W, x): """Resampling based on an interpolated CDF, as described in Malik and Pitt. Parameters ---------- W: (N,) array weights x: (N,) array particles Returns ------- xrs: (N,) array the resampled particles """ N = W.shape[...
python
def _construct_sharded(self): """Construct command line strings for a sharded cluster.""" current_version = self.getMongoDVersion() num_mongos = self.args['mongos'] if self.args['mongos'] > 0 else 1 shard_names = self._get_shard_names(self.args) # create shards as stand-alones...
python
def are_worth_chaining(parser, to_type: Type[S], converter: Converter[S, T]) -> bool: """ Utility method to check if it makes sense to chain this parser with the given destination type, and the given converter to create a parsing chain. Returns True if it brings value to chain them. To ...
java
private String[] superTypes( ObjectType cmisType ) { if (cmisType.getBaseTypeId() == BaseTypeId.CMIS_FOLDER) { return new String[] {JcrConstants.NT_FOLDER}; } if (cmisType.getBaseTypeId() == BaseTypeId.CMIS_DOCUMENT) { return new String[] {JcrConstants.NT_FILE}; ...
java
public static Version parse(String version) { Assert.hasText(version, "Version must not be null o empty!"); String[] parts = version.trim().split("\\."); int[] intParts = new int[parts.length]; for (int i = 0; i < parts.length; i++) { String input = i == parts.length - 1 ? parts[i].replaceAll(...
java
public static String jsonNameVal(final String indent, final String name, final String val) { StringBuilder sb = new StringBuilder(); sb.append(indent); sb.append("\""); sb.append(name); sb.append("\": "); if (val != null) ...
java
public static <T> QBean<T> fields(Path<? extends T> type, Map<String, ? extends Expression<?>> bindings) { return new QBean<T>(type.getType(), true, bindings); }
python
def parse_value(self, text: str) -> Optional[bool]: """Parse boolean value. Args: text: String representation of the value. """ if text == "true": return True if text == "false": return False
java
public static boolean isPublicStatic(Field f) { final int modifiers = f.getModifiers(); return Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers); }
java
@Override @LogarithmicTime(amortized = true) public Handle<K, V> insert(K key) { return insert(key, null); }
java
public static File create(FileCreateParams params, RequestOptions options) throws StripeException { checkNullTypedParams(classUrl(File.class, Stripe.getUploadBase()), params); return create(params.toMap(), options); }
java
protected void doExecuteCommand() { if (this.commandExecutor instanceof ParameterizableActionCommandExecutor) { ((ParameterizableActionCommandExecutor) this.commandExecutor).execute(getParameters()); } else { if (this.commandExecutor != null) { this.commandExecutor...
python
def tf(cluster): """ Computes the term frequency and stores it as a dictionary :param cluster: the cluster that contains the metadata :return: tf dictionary """ counts = dict() words = cluster.split(' ') for word in words: counts[word] = count...
python
def _get_value(self, var): """Return value of variable in solution.""" return self._problem._p.get_value(self._problem._variables[var])
java
int numNodes(Block b) { BlockInfo info = blocks.get(b); return info == null ? 0 : info.numNodes(); }
java
public Response put(Session session, String path, InputStream inputStream, String fileNodeType, String contentNodeType, List<String> mixins, List<String> tokens, MultivaluedMap<String, String> allowedAutoVersionPath) { try { Node node = null; boolean isVer...
java
public ListZonesResponse listZones(AbstractBceRequest request) { InternalRequest internalRequest = this.createRequest(request, HttpMethodName.GET, ZONE); return invokeHttpClient(internalRequest, ListZonesResponse.class); }
python
def outputWord(self): """Output report to word docx """ import docx from docx.enum.text import WD_ALIGN_PARAGRAPH doc = docx.Document() doc.styles['Normal'].paragraph_format.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY doc.add_heading(self.title, level...
java
public void sendWithBulkProcessor(IndexRequest indexRequest) { Optional.ofNullable(this.bulkProcessor) .orElseGet(() -> setAndReturnBulkProcessor(BulkProcessor .builder(jmESClient, bulkProcessorListener).build())) .add(indexRequest); }
java
public void writeHeadersTo(final CacheResponse pResponse) { String[] headers = getHeaderNames(); for (String header : headers) { // HACK... // Strip away internal headers if (HTTPCache.HEADER_CACHED_TIME.equals(header)) { continue; }...
python
def Address(self): """ Get the wallet address associated with the token. Returns: str: base58 encoded string representing the wallet address. """ if self._address is None: self._address = Crypto.ToAddress(self.ScriptHash) return self._address
java
public synchronized void removeObserver(final String notification, final ApptentiveNotificationObserver observer) { final ApptentiveNotificationObserverList list = findObserverList(notification); if (list != null) { list.removeObserver(observer); } }
java
protected static Variable findTargetVariable(VariableExpression ve) { final Variable accessedVariable = ve.getAccessedVariable() != null ? ve.getAccessedVariable() : ve; if (accessedVariable != ve) { if (accessedVariable instanceof VariableExpression) return findTargetVariabl...
java
public static DiscreteLogLinearFactor fromFeatureGeneratorSparse(DiscreteFactor factor, FeatureGenerator<Assignment, String> featureGen) { Iterator<Outcome> iter = factor.outcomeIterator(); Set<String> featureNames = Sets.newHashSet(); while (iter.hasNext()) { Outcome o = iter.next(); for ...
python
def id(self, peer=None, **kwargs): """Shows IPFS Node ID info. Returns the PublicKey, ProtocolVersion, ID, AgentVersion and Addresses of the connected daemon or some other node. .. code-block:: python >>> c.id() {'ID': 'QmVgNoP89mzpgEAAqK8owYoDEyB97MkcGvoWZir8o...
python
def peakdelta(v, delta, x=None): """ Returns two arrays function [maxtab, mintab]=peakdelta(v, delta, x) %PEAKDET Detect peaks in a vector % [MAXTAB, MINTAB] = peakdelta(V, DELTA) finds the local % maxima and minima ("peaks") in the vector V. % MAXTAB and MINTAB consist...
python
def table(self): """Return a large string of the entire table ready to be printed to the terminal.""" dimensions = max_dimensions(self.table_data, self.padding_left, self.padding_right)[:3] return flatten(self.gen_table(*dimensions))
java
public void setSearchableInfo(SearchableInfo searchable) { mSearchable = searchable; if (mSearchable != null) { updateSearchAutoComplete(); updateQueryHint(); } // Cache the voice search capability mVoiceButtonEnabled = hasVoiceSearch(); if (mVoic...
java
protected PrintJob createJob(final PrintJobEntry entry) { //CHECKSTYLE:ON PrintJob job = this.context.getBean(PrintJob.class); job.setEntry(entry); job.setSecurityContext(SecurityContextHolder.getContext()); return job; }
python
def _xpathDict(xml, xpath, cls, parent, **kwargs): """ Returns a default Dict given certain information :param xml: An xml tree :type xml: etree :param xpath: XPath to find children :type xpath: str :param cls: Class identifying children :type cls: inventory.Resource :param parent: Pare...
python
def delete_asset_content(self, asset_content_id): """Deletes content from an ``Asset``. arg: asset_content_id (osid.id.Id): the ``Id`` of the ``AssetContent`` raise: NotFound - ``asset_content_id`` is not found raise: NullArgument - ``asset_content_id`` is ``null`` ...
java
private String[] splitSeqName(String sequenceName) { String[] result = new String[3]; String[] barSplit = sequenceName.split("/"); if (barSplit.length == 2) { result[0] = barSplit[0]; String[] positions = barSplit[1].split("-"); if (positions.length == 2) { result[1] = positions[0]; result[2] = ...
python
def formatted(self): """str: The BIC separated in the blocks bank-, country- and location-code.""" formatted = ' '.join([self.bank_code, self.country_code, self.location_code]) if self.branch_code: formatted += ' ' + self.branch_code return formatted
python
def run(self, context=None, stdout=None, stderr=None): "Like execute, but records a skip if the should_skip method returns True." if self.should_skip(): self._record_skipped_example(self.formatter) self.num_skipped += 1 else: self.execute(context, stdout, stde...
python
def buy_open_order_quantity(self): """ [int] 买方向挂单量 """ return sum(order.unfilled_quantity for order in self.open_orders if order.side == SIDE.BUY and order.position_effect == POSITION_EFFECT.OPEN)
python
def write_single_coil(self, starting_address, value): """ Write single Coil to Master device (Function code 5) starting_address: Coil to be written value: Coil Value to be written """ self.__transactionIdentifier+=1 if (self.__ser is not None): if (se...
java
public static byte[] encryptAES2Base64(byte[] data, byte[] key) { try { return Base64.getEncoder().encode(encryptAES(data, key)); } catch (Exception e) { return null; } }
python
def parse_response(self, response): """ Parse the response and build a `scanboo_common.http_client.HttpResponse` object. For successful responses, convert the json data into a dict. :param response: the `requests` response :return: [HttpResponse] response object """ ...
java
private void processEnumJavadoc(Options.OptionInfo oi) { Enum<?>[] constants = (Enum<?>[]) oi.baseType.getEnumConstants(); if (constants == null) { return; } oi.enumJdoc = new LinkedHashMap<>(); for (Enum<?> constant : constants) { assert oi.enumJdoc != null : "@AssumeAssertion(nullnes...
python
def labelTextWidth(label): """ Returns the width of label text of the label in pixels. IMPORTANT: does not work when the labels are styled using style sheets. Unfortunately it is possible to retrieve the settings (e.g. padding) that were set by the style sheet without parsing the style she...
python
def list_external_jar_dependencies(self, binary): """Returns the external jar dependencies of the given binary. :param binary: The jvm binary target to list transitive external dependencies for. :type binary: :class:`pants.backend.jvm.targets.jvm_binary.JvmBinary` :returns: A list of (jar path, coordin...
java
public void setViewEnabled(boolean enable) { if (enable && mView == null) { mView = makeView(); } if (mView != null) { mView.setViewEnabled(enable); } }
python
def set_torrent_download_limit(self, infohash_list, limit): """ Set download speed limit of the supplied torrents. :param infohash_list: Single or list() of infohashes. :param limit: Speed limit in bytes. """ data = self._process_infohash_list(infohash_list) data...
python
def _get_true_palette_entry(self, name, digits): ''' Compute truecolor entry, once on the fly. values must become sequence of decimal int strings: ('1', '2', '3') ''' values = None type_digits = type(digits) is_fbterm = (env.TERM == 'fbterm') # sigh if 'tru...
python
def retry(self, delay=0, group=None, message=None): '''Retry this job in a little bit, in the same queue. This is meant for the times when you detect a transient failure yourself''' args = ['retry', self.jid, self.queue_name, self.worker_name, delay] if group is not None and message is n...
java
@Override public String newId(final RootDocument rootDocument) { return newId(mongoTemplate, FamilyDocumentMongo.class, rootDocument.getFilename(), "F"); }
java
private void generateEncode(TypeToken<?> outputType, Schema schema) { TypeToken<?> callOutputType = getCallTypeToken(outputType, schema); Method encodeMethod = getMethod(void.class, "encode", callOutputType.getRawType(), Encoder.class); if (!Object.class.equals(callOutputType.getRawType())) { // Gen...
python
def send_mail(self, sender, subject, recipients, message, response_id=None, html_message=False): """Send an email using EBUio features. If response_id is set, replies will be send back to the PlugIt server.""" params = { 'sender': sender, 'subject': subject, 'dests':...
java
protected TokenList.Token createOp( TokenList.Token left , TokenList.Token op , TokenList.Token right , TokenList tokens , Sequence sequence ) { Operation.Info info = functions.create(op.symbol, left.getVariable(), right.getVariable()); sequence.addOperation(in...
python
def write_out(self, output): """Banana banana """ for page in self.walk(): ext = self.project.extensions[page.extension_name] ext.write_out_page(output, page)
python
def get_saved_search(self, id, **kwargs): # noqa: E501 """Get a specific saved search # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_saved_search(id, asy...
java
private static BigInteger bigTenToThe(int n) { if (n < 0) return BigInteger.ZERO; if (n < BIG_TEN_POWERS_TABLE_MAX) { BigInteger[] pows = BIG_TEN_POWERS_TABLE; if (n < pows.length) return pows[n]; else return expandBigInteg...
java
public static java.util.List<com.liferay.commerce.price.list.model.CommercePriceList> getCommercePriceListsByUuidAndCompanyId( String uuid, long companyId) { return getService() .getCommercePriceListsByUuidAndCompanyId(uuid, companyId); }
python
def get_activity_admin_session(self, proxy): """Gets the ``OsidSession`` associated with the activity administration service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.learning.ActivityAdminSession) - an ``ActivityAdminSession`` raise: NullArgument - ``pro...
python
def auto_stratify(scores, **kwargs): """Generate Strata instance automatically Parameters ---------- scores : array-like, shape=(n_items,) ordered array of scores which quantify the classifier confidence for the items in the pool. High scores indicate a high confidence that the ...
java
public static boolean isRegisteredOnServer(Context context) { final SharedPreferences prefs = getGCMPreferences(context); boolean isRegistered = prefs.getBoolean(PROPERTY_ON_SERVER, false); Log.v(TAG, "Is registered on server: " + isRegistered); if (isRegistered) { // checks ...
python
def add_multiple(self, *users): """Add multiple users to the group at once. Each given user must be a dictionary containing a nickname and either an email, phone number, or user_id. :param args users: the users to add :return: a membership request :rtype: :class:`Member...
java
public void matchSet(Hashtable elements, int combine_op, int compare_op) throws DBException { // Delete the old search criteria criteria = new Criteria(); // If compare_op is not a binary operator, throw an exception if ((compare_op & BINARY_OPER_MA...
java
@Nonnull public final LBiByteFunctionBuilder<R> withHandling(@Nonnull HandlingInstructions<RuntimeException, RuntimeException> handling) { Null.nonNullArg(handling, "handling"); if (this.handling != null) { throw new UnsupportedOperationException("Handling is already set for this builder."); } this.handling...
python
def ecef2geodetic(x: float, y: float, z: float, ell: Ellipsoid = None, deg: bool = True) -> Tuple[float, float, float]: """ convert ECEF (meters) to geodetic coordinates Parameters ---------- x : float or numpy.ndarray of float target x ECEF coordinate (meters) y : flo...
python
def info(request, message, extra_tags='', fail_silently=False): """Adds a message with the ``INFO`` level.""" add_message(request, constants.INFO, message, extra_tags=extra_tags, fail_silently=fail_silently)
java
@Override public void visit(NodeVisitor v) { if (v.visit(this)) { for (AstNode var : variables) { var.visit(v); } } }
java
@SuppressWarnings("unchecked") public static Map<String, Object> normaliseAndValidateQuery(Map<String, Object> query) throws QueryException{ boolean isWildCard = false; if (query.isEmpty()) { isWildCard = true; } // First expand the query to include a leading compound pr...
java
@Override public MessageRepresentation getMessage(int commandCode, long applicationId, boolean isRequest) { if (!this.configured) { return null; } MessageRepresentation key = new MessageRepresentationImpl(commandCode, applicationId, isRequest); return this.commandMap.get(key); }
java
double refine_clusters(List<Cluster<K>> clusters) { double[] norms = new double[clusters.size()]; int offset = 0; for (Cluster cluster : clusters) { norms[offset++] = cluster.composite_vector().norm(); } double eval_cluster = 0.0; int loop_count =...
java
private static String[] getAllowedMethods(String[] existingMethods) { int listCapacity = existingMethods.length + 1; List<String> allowedMethods = new ArrayList<>(listCapacity); allowedMethods.addAll(Arrays.asList(existingMethods)); allowedMethods.add(METHOD_PATCH); return all...
java
@Override public <A, B, C, D> P4<A, B, C, D> asProc4() { return new P4<>(this, args); }
java
public int layerSize(String layerName) { Layer l = getLayer(layerName); if(l == null){ throw new IllegalArgumentException("No layer with name \"" + layerName + "\" exists"); } org.deeplearning4j.nn.conf.layers.Layer conf = l.conf().getLayer(); if (conf == null || !(co...