language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public EntryStream<K, V> filterKeys(Predicate<? super K> keyPredicate) { return filter(e -> keyPredicate.test(e.getKey())); }
python
def cancel_order(self, order_param): """Cancel an open order. Parameters ---------- order_param : str or Order The order_id or order object to cancel. """ order_id = order_param if isinstance(order_param, zipline.protocol.Order): order_id ...
java
@Override protected void doHandle(CommandContext ctx) throws CommandLineException { final TryCatchFinallyControlFlow flow = TryCatchFinallyControlFlow.get(ctx); if(flow == null) { throw new CommandLineException("end-if may appear only at the end of try-catch-finally control flow"); ...
java
protected void checkFallback(String elementType) { if (hasValidFallback) { hasValidFallback = false; } else { report.message(MessageId.MED_002, EPUBLocation.create(path, parser.getLineNumber(), parser.getColumnNumber()), elementType); } }
python
def create_primary_zone_by_upload(self, account_name, zone_name, bind_file): """Creates a new primary zone by uploading a bind file Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. bind_file --...
python
def main(): """This program prints doubled values!""" import numpy X=arange(.1,10.1,.2) #make a list of numbers Y=myfunc(X) # calls myfunc with argument X for i in range(len(X)): print(X[i],Y[i])
java
public void marshall(ServiceError serviceError, ProtocolMarshaller protocolMarshaller) { if (serviceError == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(serviceError.getServiceErrorId(), SERVICEER...
python
def reduce_l2(attrs, inputs, proto_obj): """Reduce input tensor by l2 normalization.""" new_attrs = translation_utils._fix_attribute_names(attrs, {'axes':'axis'}) return 'norm', new_attrs, inputs
java
public Collection<AlertPolicy> list(List<String> queryParams) { return HTTP.GET("/v2/alerts_policies.json", null, queryParams, ALERT_POLICIES).get(); }
java
public static BooleanIsEqual isEqual(BooleanExpression left, Object constant) { if (!(constant instanceof Boolean)) throw new IllegalArgumentException("constant is not a Boolean"); return new BooleanIsEqual(left, constant((Boolean)constant)); }
java
public void setLayer(VectorLayer layer) { this.layer = layer; if (layer == null) { clear(); } else { empty(); updateFields(); } }
python
def _to_dsn(hosts): """Convert a host URI into a dsn for aiopg. >>> _to_dsn('aiopg://myhostname:4242/mydb') 'postgres://crate@myhostname:4242/mydb' >>> _to_dsn('aiopg://myhostname:4242') 'postgres://crate@myhostname:4242/doc' >>> _to_dsn('aiopg://hoschi:pw@myhostname:4242/doc?sslmode=require'...
java
protected static Bundle buildCommonArgsBundle(int pickerId, String title, String positiveButtonText, String negativeButtonText, boolean enableMultipleSelection, int[] selectedItemIndices) { Bundle args = new Bundle(); args.putInt(ARG_PICKER_ID, pickerId); args.putString(ARG_TITLE, title); ...
python
def get_valid_actions(self) -> Dict[str, Tuple[torch.Tensor, torch.Tensor, List[int]]]: """ Returns the valid actions in the current grammar state. See the class docstring for a description of what we're returning here. """ actions = self._valid_actions[self._nonterminal_stack[-...
python
def predict_proba(self, L): """ Args: L: An [n, m] scipy.sparse matrix of labels Returns: output: A [n, k] np.ndarray of probabilistic labels """ n = L.shape[0] Y_p = np.random.rand(n, self.k) Y_p /= Y_p.sum(axis=1).reshape(-1, 1) r...
python
def invariant(arg1, arg2=None): """ Specify a class invariant described by `description` and tested by `predicate`. """ desc = "" predicate = lambda x: x if isinstance(arg1, str): desc = arg1 predicate = arg2 else: desc = get_function_source(arg1) predic...
java
protected void load() { properties = new Properties(); String filename = getFilename(); try { URL url = ClassHelper.getResource(filename); if (url == null) { url = (new File(filename)).toURL(); } ...
python
def compute_region_border(start, end): """ given the buffer start and end indices of a range, compute the border edges that should be drawn to enclose the range. this function currently assumes 0x10 length rows. the result is a dictionary from buffer index to Cell instance. the Cell instance ...
python
def merge_errors(errors1, errors2): """Deeply merges two error messages. Error messages can be string, list of strings or dict of error messages (recursively). Format is the same as accepted by :exc:`ValidationError`. Returns new error messages. """ if errors1 is None: return errors2 ...
java
public SlaveConnectionInfo slaveConnectionInfo() { if (isMaster()) throw new IllegalStateException("Unable to determine slave connection info. This is a master node"); return SlaveConnectionInfo.builder().connectionUrl(subscriber.connectionUrl()).masterUrl(publishMasterUrl) ...
java
@Nullable protected <T> T convert(Object source, Class<T> targetType) { return this.conversionService.convert(source, targetType); }
java
public MonthDay with(Month month) { Jdk8Methods.requireNonNull(month, "month"); if (month.getValue() == this.month) { return this; } int day = Math.min(this.day, month.maxLength()); return new MonthDay(month.getValue(), day); }
java
public static <T> Lazy<T> get(Supplier<? extends T> supplier) { return new SuppliedLazy<T>(supplier); }
java
private void determineDefaultAccessTypeAndMetaCompleteness() { for ( EntityMappings mappings : entityMappings ) { PersistenceUnitMetadata meta = mappings.getPersistenceUnitMetadata(); if ( meta != null ) { if ( meta.getXmlMappingMetadataComplete() != null ) { context.mappingDocumentFullyXmlConfigured( ...
java
@Override public KeyTransaction deserialize(JsonElement element, Type type, JsonDeserializationContext context) throws JsonParseException { JsonObject obj = element.getAsJsonObject(); JsonElement kt = obj.get("key_transaction"); if(kt != null && kt.isJsonObject()) ret...
java
@SuppressWarnings({ "null", "unused" }) public @NotNull SuffixBuilder put(@NotNull String key, @NotNull Object value) { if (key == null) { throw new IllegalArgumentException("Key must not be null"); } if (value != null) { validateValueType(value); parameterMap.put(key, value); } ...
python
def InputSplines(seq_length, n_bases=10, name=None, **kwargs): """Input placeholder for array returned by `encodeSplines` Wrapper for: `keras.layers.Input((seq_length, n_bases), name=name, **kwargs)` """ return Input((seq_length, n_bases), name=name, **kwargs)
java
public PagedList<RecommendationInner> listHistoryForWebAppNext(final String nextPageLink) { ServiceResponse<Page<RecommendationInner>> response = listHistoryForWebAppNextSinglePageAsync(nextPageLink).toBlocking().single(); return new PagedList<RecommendationInner>(response.body()) { @Overrid...
java
@Override public <X> EmbeddableType<X> embeddable(Class<X> paramClass) { EmbeddableType embeddableType = (EmbeddableType) embeddables.get(paramClass); if (embeddableType == null) { throw new IllegalArgumentException("Not a embeddable type, {class: " + paramClass + "}");...
python
def collect_impl(self): """ emits change instances based on the delta of the two distribution directories """ ld = self.ldata rd = self.rdata deep = not self.shallow for event, entry in compare(ld, rd): if deep and fnmatches(entry, *JAR_PATTE...
java
private void convertWordNetToFlat(Properties properties) throws SMatchException { InMemoryWordNetBinaryArray.createWordNetCaches(GLOBAL_PREFIX + SENSE_MATCHER_KEY, properties); WordNet.createWordNetCaches(GLOBAL_PREFIX + LINGUISTIC_ORACLE_KEY, properties); }
java
public ListConfigurationRevisionsResult withRevisions(ConfigurationRevision... revisions) { if (this.revisions == null) { setRevisions(new java.util.ArrayList<ConfigurationRevision>(revisions.length)); } for (ConfigurationRevision ele : revisions) { this.revisions.add(ele...
java
private void handleArgPropertyFile(final String arg, final Deque<String> args) { final Map.Entry<String, String> entry = parse(arg.substring(2), args); if (entry.getValue() == null) { throw new BuildException("You must specify a property filename when using the --propertyfile argument"); ...
java
@Nullable @ReturnsMutableCopy public ICommonsList <MimeTypeInfo> getAllInfosOfMimeType (@Nullable final IMimeType aMimeType) { if (aMimeType == null) return null; final ICommonsList <MimeTypeInfo> ret = m_aRWLock.readLocked ( () -> m_aMapMimeType.get (aMimeType)); // Create a copy if present ...
java
public static aaasession[] get_filtered(nitro_service service, String filter) throws Exception{ aaasession obj = new aaasession(); options option = new options(); option.set_filter(filter); aaasession[] response = (aaasession[]) obj.getfiltered(service, option); return response; }
java
private TripleIterator getTripleIterator(final Set<Triple> set) { return new TripleIterator() { private final Iterator<Triple> _iter = set.iterator(); @Override public boolean hasNext() { return _iter.hasNext(); } @Override ...
java
public boolean removeConnection(Object c) { if (Tracer.isEnabled()) Tracer.returnConnection(cm.getPool().getConfiguration().getId(), mcp, this, c); if (connectionTraces != null) connectionTraces.remove(c); return connectionHandles.remove(c); }
java
@BetaApi public final Operation setProxyHeaderTargetTcpProxy( String targetTcpProxy, TargetTcpProxiesSetProxyHeaderRequest targetTcpProxiesSetProxyHeaderRequestResource) { SetProxyHeaderTargetTcpProxyHttpRequest request = SetProxyHeaderTargetTcpProxyHttpRequest.newBuilder() .setTa...
java
@Override public boolean hasContentsOfAllSources() { if (sourcesContent == null) { return false; } return this.sourcesContent.size() >= this._sources.size() && !this.sourcesContent.stream().anyMatch(sc -> sc == null); }
java
public static List<File> listFile(File rootDir) { return Files.fileTreeTraverser().preOrderTraversal(rootDir).filter(Files.isFile()).toList(); }
python
def highlight_current_cell(self): """Highlight current cell""" if self.cell_separators is None or \ not self.highlight_current_cell_enabled: return cursor, whole_file_selected, whole_screen_selected =\ self.select_current_cell_in_visible_portion() ...
python
def run(self): """Threading callback""" self.viewing = True while self.viewing and self._lock.acquire(): try: line = self._readline() except: pass else: logger.info(line) self._lock.release() ...
python
def _create_chord_entry(task_id, task_class, message_body, user_id): """ Create and update status records for a new :py:class:`UserTaskMixin` in a Celery chord. """ args = message_body['args'] kwargs = message_body['kwargs'] arguments_dict = task_class.arguments_as_dict(*args, **kwargs) name...
java
@Pure @Inline(value="$1.multiply($2)") public static BigDecimal operator_multiply(BigDecimal a, BigDecimal b) { return a.multiply(b); }
python
def to_dict(self): """ :return dict: This object serialized to a dict """ result = {} for name in self.__dict__: if name.startswith("_"): continue key = name.replace("_", "-") attr = getattr(self, name) result[key] ...
python
def set_handler(self, handler, start_heartbeat=True): """ Set active handler for the session @param handler: Associate active cyclone handler with the session @param start_heartbeat: Should session start heartbeat immediately """ # Check if session already has associated handle...
python
def BFS(G, start): """ Algorithm for breadth-first searching the vertices of a graph. """ if start not in G.vertices: raise GraphInsertError("Vertex %s doesn't exist." % (start,)) color = {} pred = {} dist = {} queue = Queue() queue.put(start) for vertex in G.v...
python
def build_message_key(self, message) -> str: """Given a message, return its globally-unique key. Parameters: message(Message) Returns: str """ message_key = "%(namespace)s:%(queue_name)s:%(actor_name)s:%(message_id)s" % { "namespace": self.namesp...
java
public PlainChangesLog updateNodeType(NodeTypeData ancestorDefinition, NodeTypeData recipientDefinition, Map<InternalQName, NodeTypeData> volatileNodeTypes) throws ConstraintViolationException, RepositoryException { if (!ancestorDefinition.getName().equals(recipientDefinition.getName())) { ...
python
def download_file_powershell(url, target): """ Download the file at url to target using Powershell (which will validate trust). Raise an exception if the command cannot complete. """ target = os.path.abspath(target) cmd = [ 'powershell', '-Command', "(new-object System.Ne...
java
public static <T> Stream<T> parallelConcat(final Collection<? extends Stream<? extends T>> c, final int readThreadNum, final int queueSize) { if (N.isNullOrEmpty(c)) { return Stream.empty(); } final AtomicInteger threadCounter = new AtomicInteger(c.size()); final Array...
java
public void unregisterNamespace(String prefix) throws NamespaceException, RepositoryException { unregisterNamespace(prefix, true); if (started && rpcService != null) { try { rpcService.executeCommandOnAllNodes(unregisterNamespace, false, id, prefix); } ...
java
@Override public Asset getAsset(final String assetId) throws IOException, BadVersionException, RequestFailureException { return getAsset(assetId, true); }
python
def _identify_poly(core): """Specification for a polynomial.""" return core.A, core.dim, core.shape, core.dtype
java
public static ChaincodeEndorsementPolicy fromBytes(byte[] policyAsBytes) { ChaincodeEndorsementPolicy ret = new ChaincodeEndorsementPolicy(); ret.policyBytes = new byte[policyAsBytes.length]; System.arraycopy(policyAsBytes, 0, ret.policyBytes, 0, policyAsBytes.length); return ret; ...
python
def get_peers(self, id=None, endpoint=None): """ Get the current peers of a remote node Args: id: (int, optional) id to use for response tracking endpoint: (RPCEndpoint, optional) endpoint to specify to use Returns: json object of the result or the er...
java
@Override public Promise get(String key) { if (status.get() == STATUS_CONNECTED) { try { return client.get(key).then(in -> { if (in != null) { byte[] source = in.asBytes(); if (source != null) { try { Tree root = serializer.read(source); Tree content = root.ge...
java
public static Rule createDefaultPointRule() { Graphic graphic = sf.createDefaultGraphic(); Mark circleMark = sf.getCircleMark(); circleMark.setFill(sf.createFill(ff.literal("#" + Integer.toHexString(Color.RED.getRGB() & 0xffffff)))); circleMark.setStroke(sf.createStroke(ff.literal("#" + ...
java
@Override protected List<OUT> executeOnCollections(List<IN> input, RuntimeContext ctx, ExecutionConfig executionConfig) throws Exception { FlatMapFunction<IN, OUT> function = userFunction.getUserCodeObject(); FunctionUtils.setFunctionRuntimeContext(function, ctx); FunctionUtils.openFunction(function, paramete...
java
public AdjustableClock withOffset( int offset, TimeUnit unit ) { if (unit == null) { throw new NullPointerException("Missing offset unit."); } else if ( (this.offsetAmount == offset) && (this.offsetUnit == unit) ) { return this...
java
@Override public EEnum getIfcSpaceHeaterTypeEnum() { if (ifcSpaceHeaterTypeEnumEEnum == null) { ifcSpaceHeaterTypeEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(1066); } return ifcSpaceHeaterTypeEnumEEnum; }
python
def count_jobs_to_dequeue(self): """ Returns the number of jobs that can be dequeued right now from the queue. """ # timed ZSET if self.is_timed: return context.connections.redis.zcount( self.redis_key, "-inf", time.time()) # ...
python
def firmware_download_input_protocol_type_ftp_protocol_ftp_file(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") firmware_download = ET.Element("firmware_download") config = firmware_download input = ET.SubElement(firmware_download, "input") ...
java
public void cacheDestroyed(Cache c) { synchronized (lock) { cacheNames.remove(c.getName()); sendDestroyedEvent(c); } }
java
public void marshall(WriteApplicationSettingsRequest writeApplicationSettingsRequest, ProtocolMarshaller protocolMarshaller) { if (writeApplicationSettingsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarsha...
java
public alluxio.grpc.FileSystemCommand getCommand() { return command_ == null ? alluxio.grpc.FileSystemCommand.getDefaultInstance() : command_; }
java
@Nonnull public static <R> LByteFunctionBuilder<R> byteFunction(Consumer<LByteFunction<R>> consumer) { return new LByteFunctionBuilder(consumer); }
java
public synchronized boolean reloadAllConfig(boolean init) throws IOException, SAXException, ParserConfigurationException, JSONException { if (!isConfigChanged(init)) { return false; } reloadConfig(); reloadPoolsConfig(); this.lastSuccessfulReload = ClusterManager.clock.getTime(); ret...
java
public PdfContentByte getDuplicate() { PdfPatternPainter tpl = new PdfPatternPainter(); tpl.writer = writer; tpl.pdf = pdf; tpl.thisReference = thisReference; tpl.pageResources = pageResources; tpl.bBox = new Rectangle(bBox); tpl.xstep = xstep; tpl.ystep =...
java
protected <T extends CSSProperty> boolean genericOneIdent(Class<T> type, Declaration d, Map<String, CSSProperty> properties) { if (d.size() != 1) return false; return genericTermIdent(type, d.get(0), ALLOW_INH, d.getProperty(), properties); }
python
def users_identity(self, **kwargs) -> SlackResponse: """Get a user's identity.""" self._validate_xoxp_token() return self.api_call("users.identity", http_verb="GET", params=kwargs)
python
def subgroup(self, t, i): """Handle parenthesis.""" # (?flags) flags = self.get_flags(i, self.version == _regex.V0) if flags: self.flags(flags[2:-1]) return [flags] # (?#comment) comments = self.get_comments(i) if comments: re...
python
def merge(self, branch, destination="master"): """ Merge the the given WIP branch to master (or destination, if specified) If the merge fails, the merge will be aborted and then a MergeException will be thrown. The message of the MergeException will be the "git status" o...
java
private void parseMolCXSMILES(String title, IAtomContainer mol) { CxSmilesState cxstate; int pos; if (title != null && title.startsWith("|")) { if ((pos = CxSmilesParser.processCx(title, cxstate = new CxSmilesState())) >= 0) { // set the correct title ...
python
def r2z(r): """ Function that calculates the Fisher z-transformation Parameters ---------- r : int or ndarray Correlation value Returns ---------- result : int or ndarray Fishers z transformed correlation value """ with np.errstate(invalid='ignore', divide='ig...
python
def addFile(self, path, msg=""): """Adds a file to the version""" item = Item.from_path(repo=self.repo, path=path) self.addItem(item)
python
def get_td_from_final_mass_spin(template=None, taper=None, distance=None, **kwargs): """Return time domain ringdown with all the modes specified. Parameters ---------- template: object An object that has attached properties. This can be used to substitute ...
java
public void warning(String format, Object... args) { if (isLoggable(WARNING)) { logIt(WARNING, String.format(format, args)); } }
python
def shear_mod(self): """Strain-compatible shear modulus [kN//m²].""" try: value = self._shear_mod.value except AttributeError: value = self._shear_mod return value
python
def _read_http_settings(self, size, kind, flag): """Read HTTP/2 SETTINGS frames. Structure of HTTP/2 SETTINGS frame [RFC 7540]: +-----------------------------------------------+ | Length (24) | +---------------+---------------+------...
java
private void postCommit(DbSession dbSession, Collection<String> logins, Collection<EsQueueDto> items) { index(dbSession, items); }
java
public static Double getDouble(Map<?, ?> map, Object key) { return get(map, key, Double.class); }
python
def read_windows_environ(): """Returns a unicode dict of the Windows environment. Raises: WindowsEnvironError """ res = winapi.GetEnvironmentStringsW() if not res: raise ctypes.WinError() res = ctypes.cast(res, ctypes.POINTER(ctypes.c_wchar)) done = [] current = u"" ...
python
def validate(schema, handler=None, status=400, **kw): """ Used to decorate a Pecan controller with form creation for GET | HEAD and form validation for anything else (e.g., POST | PUT | DELETE ). For an HTTP POST or PUT (RFC2616 unsafe methods) request, the schema is used to validate the request bo...
java
public void add(int index, E element) { if (index > size || index < 0) throw new IndexOutOfBoundsException( "Index: " + index + ", Size: " + size); ensureCapacity(size + 1); // Increments modCount!! System.arraycopy(data, index, data, index + 1, size - index); data[index] = ele...
python
def index_data(self): '''Generate and return a dictionary of default fields to be indexed for searching (e.g., in Solr). Includes top-level object properties, Content Model URIs, and Dublin Core fields. This method is intended to be customized and extended in order to e...
python
def maps_get_rules_output_rules_op(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") maps_get_rules = ET.Element("maps_get_rules") config = maps_get_rules output = ET.SubElement(maps_get_rules, "output") rules = ET.SubElement(output, "rules...
python
def on_channel_open(self, channel): """ Input channel creation callback Queue declaration done here Args: channel: input channel """ self.in_channel.exchange_declare(exchange='input_exc', type='topic', durable=True) channel.queue_declare(callback=self...
java
@Override public MtasDataCollector<?, ?> add(String key, double valueSum, long valueN) throws IOException { if (key != null) { MtasDataCollector<?, ?> subCollector = add(key, false); setValue(newCurrentPosition, Double.valueOf(valueSum).longValue(), valueN, newCurrentExisting); r...
java
private Interest discover(BackoffRetryClient client, On<Long> onFound, On<Void> onComplete, On<Exception> onError) throws IOException { Interest interest = new Interest(topicPrefix); interest.setInterestLifetimeMilliseconds(STARTING_DISCOVERY_LIFETIME); interest.setExclude(excludeKnownPublishers()); ...
python
def read(self, chunk_size=None): """ Return chunk_size of bytes, starting from self.pos, from self.content. """ if chunk_size: data = self.content[self.pos:self.pos + chunk_size] self.pos += len(data) return data else: return self.c...
java
@Override public EClass getIfcDistributionSystem() { if (ifcDistributionSystemEClass == null) { ifcDistributionSystemEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(188); } return ifcDistributionSystemEClass; }
python
def lie_in_seg(dt, time_str, seg_duration): """ 判断datetime是否在time_str为起点的时间片内 :param dt: :param time_str: eg: '11:10:21' :param seg_duration: :return: """ minutes_of_day = time_util.get_minutes_of_day(dt) range_begin = time_util.time_str_to_minutes(time_str) if range_begin <= min...
python
def dump(self, filepath): "Attempt to dump an opened stream to path *filepath*." common.ask_overwrite(filepath) filename = os.path.basename(filepath) file_size = 0 with open(filepath, 'ab') as f: try: while True: buf = self.fd.rea...
java
public CcgParseResult parse(AnnotatedSentence sentence, ChartCost inputFilter) { AnnotatedSentence annotatedSentence = null; if (supertagger != null) { for (int i = 0; i < multitagThresholds.length; i++) { // Try parsing at each multitag threshold. If parsing succeeds, // immediately retur...
java
@Nullable public CSSUnknownRule getUnknownRuleAtIndex (@Nonnegative final int nIndex) { return m_aRules.getAtIndexMapped (r -> r instanceof CSSUnknownRule, nIndex, r -> (CSSUnknownRule) r); }
java
@BetaApi public final DiskType getRegionDiskType(ProjectRegionDiskTypeName diskType) { GetRegionDiskTypeHttpRequest request = GetRegionDiskTypeHttpRequest.newBuilder() .setDiskType(diskType == null ? null : diskType.toString()) .build(); return getRegionDiskType(request); }
java
public String getValue(String propertyName) { Property property = super.get(propertyName); if (property == null) { return null; } return property.getValue(); }
python
def get_window_by_index(self, index): " Return the Window with this index or None if not found. " for w in self.windows: if w.index == index: return w
java
public void generate(TypeElement component) { ClassName vueFactoryClassName = componentFactoryName(component); Builder vueFactoryBuilder = createFactoryBuilderClass(component, vueFactoryClassName); createGetName(vueFactoryBuilder, component); createProperties(vueFactoryClassName, vueFactoryBuilder); ...