language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public StoredObject getObject(String id) { if (id.contains("..") || id.contains("/") || id.contains("\\")) { throw Exceptions.createHandled() .withSystemErrorMessage( "Invalid object name: %s. A object name must not contain '..' '/' or ...
python
def command_ls(self): """ List names """ self.parser = argparse.ArgumentParser( description="List names of available objects") self.options_select() self.options_utils() self.options = self.parser.parse_args(self.arguments[2:]) self.show(brief=True)
java
@Override protected Operand createEndsWithExpression(final EndsWithFilter filter, final boolean not) { if (filter == null) { return null; } final String name = filter.getAttribute().getName(); final String value = AttributeUtil.getAsStringValue(filter.getAttribute()); ...
python
def FromTextFormat(cls, text): """Parse this object from a text representation.""" tmp = cls.protobuf() # pylint: disable=not-callable text_format.Merge(text, tmp) return cls.FromSerializedString(tmp.SerializeToString())
java
public PathElement getElement(int index) { final List<PathElement> list = pathAddressList; return list.get(index); }
java
public void recordFailedTask(String trackerName) { synchronized (this) { NodeUsageReport usageReport = getReportUnprotected(trackerName); usageReport.setNumFailed(usageReport.getNumFailed() + 1); } }
java
public URI getInputMap() { // return toURI(getProperty(INPUT_DITAMAP_URI)); return files.values().stream() .filter(fi -> fi.isInput) .map(fi -> getInputDir().relativize(fi.src)) .findAny() .orElse(null); }
python
def initialize_parameters(n_x, n_h, n_y): """ Argument: n_x -- size of the input layer n_h -- size of the hidden layer n_y -- size of the output layer Returns: params -- python dictionary containing your parameters: W1 -- weight matrix of shape (n_h, n_x) ...
java
public static int singleWordWangJenkinsHash(Object k) { int h = k.hashCode(); h += (h << 15) ^ 0xffffcd7d; h ^= (h >>> 10); h += (h << 3); h ^= (h >>> 6); h += (h << 2) + (h << 14); return h ^ (h >>> 16); }
python
def stop_all(self, run_order=-1): """Runs stop method on all modules less than the passed-in run_order. Used when target is exporting itself mid-build, so we clean up state before committing run files etc. """ shutit_global.shutit_global_object.yield_to_draw() # sort them so they're stopped in reverse order...
java
public void warnf(Throwable t, String format, Object... params) { doLogf(Level.WARN, FQCN, format, params, t); }
python
def on_threads_request(self, py_db, request): ''' :param ThreadsRequest request: ''' return self.api.list_threads(py_db, request.seq)
java
@NotNull public static Metadata readMetadata(@NotNull final InputStream inputStream, final long streamLength) throws ImageProcessingException, IOException { BufferedInputStream bufferedInputStream = inputStream instanceof BufferedInputStream ? (BufferedInputStream)inputStream : n...
python
def get(self, req, driver): """Get info of a network Get info of a specific netowrk with id on special cloud with: :Param req :Type object Request """ response = driver.get_network(req.params, id) data = { 'action': "get", 'contr...
java
@Override public void stop() { try { expectSupport.close(); } catch (IOException e) { log(e, Project.MSG_DEBUG); } }
python
def head_tail_middle(src): """Returns a tuple consisting of the head of a enumerable, the middle as a list and the tail of the enumerable. If the enumerable is 1 item, the middle will be empty and the tail will be None. >>> head_tail_middle([1, 2, 3, 4]) 1, [2, 3], 4 """ if len(src) == 0:...
java
public void addAttributeValue(String attributeName, String value) { if (m_entityAttributes.containsKey(attributeName)) { throw new RuntimeException("Attribute already exists with a entity type value."); } if (m_simpleAttributes.containsKey(attributeName)) { m_simpl...
java
public static Minutes from(TemporalAmount amount) { if (amount instanceof Minutes) { return (Minutes) amount; } Objects.requireNonNull(amount, "amount"); int minutes = 0; for (TemporalUnit unit : amount.getUnits()) { long value = amount.get(unit); ...
python
def create_customer_gateway(vpn_connection_type, ip_address, bgp_asn, customer_gateway_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid VPN connection type, a static IP address and a customer gateway’s Border Ga...
java
public static boolean startAny(String target, Integer toffset, String... startWith) { return startAny(target, toffset, Arrays.asList(startWith)); }
python
def execute_script(self, sql_script=None, commands=None, split_algo='sql_split', prep_statements=False, dump_fails=True, execute_fails=True, ignored_commands=('DROP', 'UNLOCK', 'LOCK')): """Wrapper method for SQLScript class.""" ss = Execute(sql_script, split_algo, prep_statements...
java
private void notifyListener(RequestResponseClass clazz, ISFSObject params, User user, Object userAgent) throws Exception { Object listener = clazz.newInstance(); setDataToListener(clazz, listener, params); invokeExecuteMethod(clazz.getExecuteMethod(), listener, userAgent); responseClient(c...
java
public void unload(String resourceId) { LoadableResource res = this.resources.get(resourceId); if (res!=null) { res.unload(); } }
python
def get_offset_topic_partition_count(kafka_config): """Given a kafka cluster configuration, return the number of partitions in the offset topic. It will raise an UnknownTopic exception if the topic cannot be found.""" metadata = get_topic_partition_metadata(kafka_config.broker_list) if CONSUMER_OFFS...
python
def fit(self, X, vocab=None, initial_embedding_dict=None, fixed_initialization=None): """Run GloVe and return the new matrix. Parameters ---------- X : array-like of shape = [n_words, n_words] The square count matrix. ...
java
public final <T extends IInvoice, L extends IInvoiceLine<T>, TL extends AInvTxLn<T>> void adjustInvoiceLns( final Map<String, Object> pReqVars, final T pInv, final List<SalesInvoiceServiceLine> pTxdLns, final AccSettings pAs, final IInvTxMeth<T, TL> pInvTxMeth) throws Exception { String tbNm =...
java
public static final StyleMap assignDOM(Document doc, String encoding, URL base, String media, boolean useInheritance, final MatchCondition matchCond) { return assignDOM(doc, encoding, base, new MediaSpec(media), useInheritance, matchCond); }
java
public static final byte[] asByteArray(WsByteBuffer[] list, int[] positions, int[] limits) { if (null == list) return null; int size = 0; for (int i = 0; i < list.length && null != list[i]; i++) { size += limits[i] - positions[i]; } if (0 == size) ...
python
def hashlib_sha256(message): """ 获取一个字符串的 sha256 哈希值 :param: * message: (string) 需要进行哈希的字符串 :return: * hashed_str: sha256 算法哈希值 """ hashlib_sha256 = hashlib.sha256() hashlib_sha256.update(message.encode('utf-8')) hashed_str = hashl...
java
public int[] get(int size) { if (array == null || size > array.length) return array = new int[size]; return array; }
python
def flatten(iterable): """convenience tool to flatten any nested iterable example: flatten([[[],[4]],[[[5,[6,7, []]]]]]) >>> [4, 5, 6, 7] flatten('hello') >>> 'hello' Parameters ---------- iterable Returns ------- flattened object """ if isite...
java
public EClass getBAG() { if (bagEClass == null) { bagEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(193); } return bagEClass; }
java
public static void exports(Xml root, CollisionGroup group) { Check.notNull(root); Check.notNull(group); final Xml node = root.createChild(NODE_COLLISION); node.writeString(ATT_GROUP, group.getName()); for (final CollisionFormula formula : group.getFormulas()) ...
python
def _add_thread(self, aThread): """ Private method to add a thread object to the snapshot. @type aThread: L{Thread} @param aThread: Thread object. """ ## if not isinstance(aThread, Thread): ## if hasattr(aThread, '__class__'): ## typename = aThr...
java
@Override public ContinueDeploymentResult continueDeployment(ContinueDeploymentRequest request) { request = beforeClientExecution(request); return executeContinueDeployment(request); }
python
async def _upgrade_websocket(self, environ): """Upgrade the connection from polling to websocket.""" if self.upgraded: raise IOError('Socket has been upgraded already') if self.server._async['websocket'] is None: # the selected async mode does not support websocket ...
java
public String getWriteMethod() { return setterName != null ? setterName : "set" + this.name.substring( 0, 1 ).toUpperCase() + this.name.substring( 1 ); }
java
public JsonWriter property(String key, Map<String, ?> map) throws IOException { Preconditions.checkArgument(!inArray(), "Cannot write a property inside an array."); writeName(key); value(map); return this; }
python
def output(self, value): """SPL output port assignment expression. Arguments: value(str): SPL expression used for an output assignment. This can be a string, a constant, or an :py:class:`Expression`. Returns: Expression: Output assignment expression that is valid as a t...
java
@Override public java.util.concurrent.Future<RemoveTagsFromResourceResult> removeTagsFromResourceAsync( com.amazonaws.handlers.AsyncHandler<RemoveTagsFromResourceRequest, RemoveTagsFromResourceResult> asyncHandler) { return removeTagsFromResourceAsync(new RemoveTagsFromResourceRequest(), asyncH...
python
def _release_version(): ''' Returns release version ''' with io.open(os.path.join(SETUP_DIRNAME, 'saltpylint', 'version.py'), encoding='utf-8') as fh_: exec_locals = {} exec_globals = {} contents = fh_.read() if not isinstance(contents, str): contents = conten...
python
def to_spans(self): "Convert the tree to a set of nonterms and spans." s = set() self._convert_to_spans(self.tree, 1, s) return s
java
protected void notifyAllPendingSenders(String message) { for (ChannelFuture future : _futureMap.values()) { future.setFailure(new Error(message)); } }
java
@JSFunction public String readChar() throws IOException { int i = getReader().read(); if (i == -1) return null; char[] charArray = { (char) i }; return new String(charArray); }
java
public static MouseEvent convertMouseEvent(Component source, MouseEvent sourceEvent, Component destination) { Point p = SwingUtilities.convertPoint( source, sourceEvent.getPoint(), destination); Component newSource = source; if (destination != null) ...
python
def lldp(device=None, interface=None, title=None, pattern=None, chassis=None, display=_DEFAULT_DISPLAY): ''' Search in the LLDP neighbors, using the following mine functions: - net.lldp Optional arguments: device Return interface data from a ce...
python
def if_match(self): """Optimistic concurrency control.""" match = True if_match = self.request.META.get('HTTP_IF_MATCH') if if_match: etag = self.etag() if etag != if_match: match = False return match
python
def get_full_name(self): """Get the full name for debugging (host_name/service_description) :return: service full name :rtype: str """ if self.is_tpl(): return "tpl-%s/%s" % (getattr(self, 'host_name', 'XxX'), self.name) if hasattr(self, 'host_name') and hasa...
python
def patch(self, request): """ Update the status of a video. """ attrs = ('edx_video_id', 'status') missing = [attr for attr in attrs if attr not in request.data] if missing: return Response( status=status.HTTP_400_BAD_REQUEST, d...
java
public List<JAXBElement<Object>> get_GenericApplicationPropertyOfParameterizedTexture() { if (_GenericApplicationPropertyOfParameterizedTexture == null) { _GenericApplicationPropertyOfParameterizedTexture = new ArrayList<JAXBElement<Object>>(); } return this._GenericApplicationProper...
java
@Override public void setWorkingDirectory(Path hadoopPath) { long startTime = System.nanoTime(); Preconditions.checkArgument(hadoopPath != null, "hadoopPath must not be null"); logger.atFine().log("GHFS.setWorkingDirectory: %s", hadoopPath); URI gcsPath = FileInfo.convertToDirectoryPath(pathCodec, ge...
python
def _raise_invalid_gzip_err(self): """ A gzip file with multiple ARC/WARC records, non-chunked has been detected. This is not valid for replay, so notify user """ frmt = 'warc/arc' if self.known_format: frmt = self.known_format frmt_up = frmt.upper() ...
python
def log_data_encode(self, id, ofs, count, data): ''' Reply to LOG_REQUEST_DATA id : Log id (from LOG_ENTRY reply) (uint16_t) ofs : Offset into the log (uint32_t) count : Numb...
java
public static int getAPDUService(final byte[] apdu) { if (apdu.length < 2) throw new KNXIllegalArgumentException("getting APDU service from [0x" + toHex(apdu, "") + "], APCI length < 2"); // high 4 bits of APCI final int apci4 = (apdu[0] & 0x03) << 2 | (apdu[1] & 0xC0) >> 6; // lowest 6 bits of APCI ...
python
def _fill_form(form): """ Fill all inputs with provided Jinja2 templates. If no field had click key, submit last element. """ clicked = False last_element = None for field in form: if field['text']: field['element'].clear() ...
java
public boolean contains(final AbstractDynamoDbStore store, final StaticBuffer key, final StaticBuffer column) { return expectedValues.containsKey(store) && expectedValues.get(store).containsKey(key) && expectedValues.get(store).get(key).containsKey(column); }
python
def upload_file(self, simple_upload_url, chunked_upload_url, file_obj, chunk_size=CHUNK_SIZE, force_chunked=False, extra_data=None): """ Generic method to upload files to AmigoCloud. Can be used for different API endpoints. `file_obj` could be a fi...
java
public static CharSink asCompressedCharSink(File f, Charset charSet) throws IOException { return asCompressedByteSink(f).asCharSink(charSet); }
java
@SafeVarargs public final ResultSet delete(final Class<?> targetClass, final Collection<String> deletingPropNames, final Object... ids) { return delete(targetClass, deletingPropNames, ids2Cond(targetClass, ids)); }
java
@Nonnull public static <R> LLongFunction<R> longFunctionFrom(Consumer<LLongFunctionBuilder<R>> buildingFunction) { LLongFunctionBuilder builder = new LLongFunctionBuilder(); buildingFunction.accept(builder); return builder.build(); }
python
def add_output(summary_output, long_output, helper): """ if the summary output is empty, we don't add it as summary, otherwise we would have empty spaces (e.g.: '. . . . .') in our summary report """ if summary_output != '': helper.add_summary(summary_output) helper.add_long_output(long_outp...
python
def _remove_previous_ned_queries( self, coordinateList): """iterate through the transient locations to see if we have recent local NED coverage of that area already **Key Arguments:** - ``coordinateList`` -- set of coordinate to check for previous queries **...
python
def _kalman_prediction_step(k, p_m , p_P, p_dyn_model_callable, calc_grad_log_likelihood=False, p_dm = None, p_dP = None): """ Desctrete prediction function Input: k:int Iteration No. Starts at 0. Total number of iterations equal to th...
java
@Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case SimpleAntlrPackage.REFERENCE_OR_LITERAL__NAME: return getName(); } return super.eGet(featureID, resolve, coreType); }
python
def wait_for_element(self, timeout=None, message='', *args, **kwds): """ Shortcut for waiting for element. If it not ends with exception, it returns that element. Detault timeout is `~.default_wait_timeout`. Same as following: .. code-block:: python selenium.webdriv...
java
public boolean inspectAnotherSameInfo(@NonNull DownloadTask task, @NonNull BreakpointInfo info, long instanceLength) { if (!task.isFilenameFromResponse()) return false; final BreakpointStore store = OkDownload.with().breakpointStore(); final BreakpointI...
python
def _make_identifier(string): """Attempt to convert string into a valid identifier by replacing invalid characters with "_"s, and prefixing with "a_" if necessary.""" string = re.sub(r"[ \-+/\\*%&$£#@.,;:'" "?<>]", "_", string) if re.match(r"^\d", string): string = "a_{0}".fo...
python
def grepPDF(self, path): """ Parse PDF files text content for keywords. Args: path: PDF file path. Returns: match: set of unique occurrences of every match. """ with open(path, 'rb') as pdf_file_obj: match = set() text = '' pdf_reader = PyPDF2.PdfFileReader(pdf_fi...
python
def workflow_list_projects(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /workflow-xxxx/listProjects API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Cloning#API-method%3A-%2Fclass-xxxx%2FlistProjects """ return DXHTTPRequest('/%s/listPr...
python
def specbits(self): """Returns the array of arguments that would be given to iptables for the current Rule. """ def host_bits(opt, optval): # handle the case where this is a negated value m = re.match(r'^!\s*(.*)', optval) if m: return ...
java
public void close() { Politician.beatAroundTheBush(() -> { if (this.prevayler != null) { this.optionalSnapshot(); this.prevayler.close(); this.prevayler = null; } }); }
java
public static MD5MD5CRC32FileChecksum valueOf(Attributes attrs ) throws SAXException { final String bytesPerCRC = attrs.getValue("bytesPerCRC"); final String crcPerBlock = attrs.getValue("crcPerBlock"); final String md5 = attrs.getValue("md5"); if (bytesPerCRC == null || crcPerBlock == null || md5...
java
@Override public void removeAllElements() { removeAllElectronContainers(); for (int f = 0; f < getAtomCount(); f++) { getAtom(f).removeListener(this); } atoms = new IAtom[growArraySize]; atomCount = 0; stereoElements.clear(); notifyChanged(); }
java
public <T> RDD<T> createRDD(ExtractorConfig<T> config) { return new DeepRDD<>(this.sc(), config); }
java
public void marshall(ImportWorkspaceImageRequest importWorkspaceImageRequest, ProtocolMarshaller protocolMarshaller) { if (importWorkspaceImageRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshal...
java
public final HlFlCnNm lazyGetHldFieldsCnvTfsNames() throws Exception { String beanName = getHldFieldsCnvTfsNamesName(); HlFlCnNm hldFieldsCnvTfsNames = (HlFlCnNm) this.beansMap.get(beanName); if (hldFieldsCnvTfsNames == null) { hldFieldsCnvTfsNames = new HlFlCnNm("fieldFromToStringConverter"); ...
java
public static Spliterator.OfLong spliterator(long[] array, int additionalCharacteristics) { return new LongArraySpliterator(Objects.requireNonNull(array), additionalCharacteristics); }
java
@Override public void setMaximumIntegerDigits(int newValue) { maximumIntegerDigits = Math.min(Math.max(0, newValue), MAXIMUM_INTEGER_DIGITS); super.setMaximumIntegerDigits((maximumIntegerDigits > DOUBLE_INTEGER_DIGITS) ? DOUBLE_INTEGER_DIGITS : maximumIntegerDigits); if (minimumI...
java
@Override protected int readData(byte[] buffer, int offset) { StringsWithLengthBlock data = new StringsWithLengthBlock().read(buffer, offset, true); m_data = data.getData(); offset = data.getOffset(); return offset; }
python
def debug_lvl_from_env(): """Read and return `DM_SQUARE_DEBUG` env var, if defined. Raises ------ RuntimeError If DM_SQUARE_DEBUG is not an int convertable value """ debug_lvl = os.environ.get('DM_SQUARE_DEBUG') if not debug_lvl: return 0 try: debug_lvl = int(de...
java
public Observable<EventSubscriptionInner> updateAsync(String scope, String eventSubscriptionName, EventSubscriptionUpdateParameters eventSubscriptionUpdateParameters) { return updateWithServiceResponseAsync(scope, eventSubscriptionName, eventSubscriptionUpdateParameters).map(new Func1<ServiceResponse<EventSubsc...
python
def __match_l(self, k, _set): """ Method for searching subranges from `_set` that overlap on `k` range. Parameters ---------- k : tuple or list or range Range for which we search overlapping subranges from `_set`. _set : set Subranges set. ...
python
def execute_with_delay(task_function, *args, **kwargs): """Run a task asynchronously after at least delay_seconds """ delay = kwargs.pop('delay', 0) if get_setting('TEST_DISABLE_ASYNC_DELAY'): # Delay disabled, run synchronously logger.debug('Running function "%s" synchronously because '...
java
public synchronized ClientInterceptor getCredentialsInterceptor( CredentialOptions credentialOptions, RetryOptions retryOptions) throws IOException, GeneralSecurityException { // Default credentials is the most likely CredentialType. It's also the only CredentialType // that can be safely cached. ...
java
public static String escapeJava(final Object target) { if (target == null) { return null; } return JavaEscape.escapeJava(target.toString()); }
python
def _setup_memory(self): """Setup Memory object for memory caching. """ if self.memory: if isinstance(self.memory, str): if self.memory == "auto": # Create a temporary folder to store the transformers of the pipeline self._cache...
java
public void add(PortBinding... portBindings) { for (PortBinding binding : portBindings) { bind(binding.getExposedPort(), binding.getBinding()); } }
python
def load_file(self, fname, table=None, sep="\t", bins=False, indexes=None): """ use some of the machinery in pandas to load a file into a table Parameters ---------- fname : str filename or filehandle to load table : str table to load the file t...
java
public Object[] buildParameters(Object[] firstParameters, Method method, QueryAdapter queryAdapter, Class<? extends Annotation> annotationType) { int parametersLength = method.getParameterTypes().length; if (firstParameters.length > 0 && parametersLength < 1) { ...
python
def _right_click(self, event): """Function bound to right click event for marker canvas""" iid = self.current_iid if iid is None: if self._menu is not None: self._menu.post(event.x, event.y) return args = (iid, (event.x_root, event.y_root)) ...
python
def json_options_to_metadata(options, add_brackets=True): """Read metadata from its json representation""" try: options = loads('{' + options + '}' if add_brackets else options) return options except ValueError: return {}
python
def parseDateText(self, dateString): """ Parse long-form date strings:: 'May 31st, 2006' 'Jan 1st' 'July 2006' @type dateString: string @param dateString: text to convert to a datetime @rtype: struct_time @return: calcu...
python
def _autobounds(self): """Simple calculation for bounds.""" bounds = {} def check(prop, compare, extreme, val): opp = min if compare is max else max bounds.setdefault(prop, val) bounds[prop] = opp(compare(bounds[prop], val), extreme) def bound_check(...
java
@Override public WebserviceSecurity getWebserviceSecurity() { if (delegate == null) { return this.webServiceSecurity; } else { return this.webServiceSecurity == null ? delegate.getWebserviceSecurity() : this.webServiceSecurity; } }
java
protected final UtlInvLine<RS, PurchaseInvoice, PurchaseInvoiceServiceLine, PurchaseInvoiceTaxLine, PurchaseInvoiceServiceTaxLine> lazyGetUtlPurSrLn( final Map<String, Object> pAddParam) throws Exception { UtlInvLine<RS, PurchaseInvoice, PurchaseInvoiceServiceLine, PurchaseInvoiceTaxLine, PurchaseIn...
python
def _forecast_model(self,beta,Z,h): """ Creates forecasted states and variances Parameters ---------- beta : np.ndarray Contains untransformed starting values for latent variables Returns ---------- a : np.ndarray Forecasted states ...
java
static void quoteListenerAndHostAttributeKeys(Node objLit, AbstractCompiler compiler) { checkState(objLit.isObjectLit()); for (Node keyNode : objLit.children()) { if (keyNode.isComputedProp()) { continue; } if (!keyNode.getString().equals("listeners") && !keyNode.getString()....
java
void seal() { if (!this.sealed && !this.contents.isReadOnly()) { Preconditions.checkState(writeEntryStartIndex < 0, "An open entry exists. Any open entries must be closed prior to sealing."); this.header.setContentLength(writePosition); this.header.commit(); this...
python
def tickOptionComputation(self, tickerId, tickType, impliedVol, delta, optPrice, pvDividend, gamma, vega, theta, undPrice): """tickOptionComputation(EWrapper self, TickerId tickerId, TickType tickType, double impliedVol, double delta, double optPrice, double pvDividend, double gamma, double vega, double theta, ...
java
public static ComplexNumber Pow(ComplexNumber z1, double n) { double norm = Math.pow(z1.getMagnitude(), n); double angle = 360 - Math.abs(Math.toDegrees(Math.atan(z1.imaginary / z1.real))); double common = n * angle; double r = norm * Math.cos(Math.toRadians(common)); ...