language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static Bip39Wallet generateBip39Wallet(String password, File destinationDirectory) throws CipherException, IOException { byte[] initialEntropy = new byte[16]; secureRandom.nextBytes(initialEntropy); String mnemonic = MnemonicUtils.generateMnemonic(initialEntropy); byt...
java
private void checkIfUpdateIsNeeded(CmsUUID structureId, String rootPath, int typeId) { try { I_CmsResourceType resType = OpenCms.getResourceManager().getResourceType(typeId); if ((resType instanceof CmsResourceTypeXmlContent) && !OpenCms.getResourceManager().matchResourc...
python
def request_hc_path_corresponds(self): """ Tells if the hc path of the request corresponds to that specified by the admin :return: a boolean that says if it corresponds or not """ uri_path = self.path.split(COAP_PREFACE) request_hc_path = uri_path[0] logger.debug...
python
def absolute_redirect_n_times(n): """Absolutely 302 Redirects n times. --- tags: - Redirects parameters: - in: path name: n type: int produces: - text/html responses: 302: description: A redirection. """ assert n > 0 if n == 1: ...
java
public DbHistory[] get_device_attribute_property_history(String devname, String attname, String propname) throws DevFailed { return databaseDAO.get_device_attribute_property_history(this, devname, attname, propname); }
java
public static base_response add(nitro_service client, dnssoarec resource) throws Exception { dnssoarec addresource = new dnssoarec(); addresource.domain = resource.domain; addresource.originserver = resource.originserver; addresource.contact = resource.contact; addresource.serial = resource.serial; addresou...
java
public static ArrayList<VictimsRecord> getRecords(InputStream in, String filename) throws IOException { ArrayList<VictimsRecord> records = new ArrayList<VictimsRecord>(); Artifact artifact = Processor.process(in, filename); scanArtifact(artifact, new ArrayOutputStream(records)); ...
python
def confirm_register_form_factory(Form): """Factory for creating a confirm register form.""" class CsrfDisabledProfileForm(ProfileForm): """Subclass of ProfileForm to disable CSRF token in the inner form. This class will always be a inner form field of the parent class `Form`. The paren...
java
public DecoderResult decode(BitMatrix bits) throws FormatException, ChecksumException { // Construct a parser and read version, error-correction level BitMatrixParser parser = new BitMatrixParser(bits); Version version = parser.getVersion(); // Read codewords byte[] codewords = parser.readCodeword...
java
public MaterialStep getCurrentStep() { if (currentStepIndex > getWidgetCount() - 1 || currentStepIndex < 0) { return null; } Widget w = getWidget(currentStepIndex); if (w instanceof MaterialStep) { return (MaterialStep) w; } return null; }
java
public void setParamTabEdDirectEditButtonStyle(String value) { try { m_userSettings.setDirectEditButtonStyle(Integer.parseInt(value)); } catch (Throwable t) { // should usually never happen } }
java
public EClass getIDEStructure() { if (ideStructureEClass == null) { ideStructureEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(392); } return ideStructureEClass; }
java
@Nonnull public static BootstrapButtonGroup createButtonAsDropDownMenuWithSeparateCaret (@Nonnull final BootstrapButton aButton, @Nonnull final Consumer <? super BootstrapDropdownMenu> aMenuItemProvider) { final BootstrapButtonGro...
java
@Override public <T> List<T> dynamicQuery(DynamicQuery dynamicQuery) { return cpRuleUserSegmentRelPersistence.findWithDynamicQuery(dynamicQuery); }
java
public Deployment deploy(URL url, Context context, ClassLoader parent) throws DeployException { FileInputStream fis = null; try { File dashRaXml = new File(url.toURI()); ResourceAdapterParser parser = new ResourceAdapterParser(); fis = new FileInputStream(dashR...
python
def write_uint16(self, word): """Write 2 bytes.""" self.write_byte(nyamuk_net.MOSQ_MSB(word)) self.write_byte(nyamuk_net.MOSQ_LSB(word))
java
public R performActionAndWaitForEvent(K eventKey, long timeout, Callback<E> action) throws InterruptedException, E { final Reference<R> reference = new Reference<>(); events.put(eventKey, reference); try { synchronized (reference) { action.action(); re...
java
public void evaluate(DoubleSolution solution){ double aux, xi, xj; double[] fx = new double[getNumberOfObjectives()]; double[] x = new double[getNumberOfVariables()]; for (int i = 0; i < solution.getNumberOfVariables(); i++) { x[i] = solution.getVariableValue(i) ; } fx[0] = 0.0; ...
java
public boolean remove(URI uri, HttpCookie ck) { // argument can't be null if (ck == null) { throw new NullPointerException("cookie is null"); } lock.lock(); try { uri = getEffectiveURI(uri); if (uriIndex.get(uri) == null) { ret...
java
public HttpClientResponseBuilder doThrowException(IOException exception) { newRule.addAction(new ExceptionAction(exception)); return new HttpClientResponseBuilder(newRule); }
java
private void nnChainCore(MatrixParadigm mat, DBIDArrayMIter prots, DistanceQuery<O> dq, PointerHierarchyRepresentationBuilder builder, Int2ObjectOpenHashMap<ModifiableDBIDs> clusters) { final DBIDArrayIter ix = mat.ix; final double[] distances = mat.matrix; final int size = mat.size; // The maximum chai...
python
def _errstr(value): """Returns the value str, truncated to MAX_ERROR_STR_LEN characters. If it's truncated, the returned value will have '...' on the end. """ value = str(value) # We won't make the caller convert value to a string each time. if len(value) > MAX_ERROR_STR_LEN: return value[:...
python
def _search(self, which, term): """ The real search method. :param which: 1 for anime, 2 for manga :param term: What to search for :rtype: list :return: list of :class:`Pymoe.Mal.Objects.Manga` or :class:`Pymoe.Mal.Objects.Anime` objects as per the type param. ""...
java
@Override public EClass getIfcSlab() { if (ifcSlabEClass == null) { ifcSlabEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI).getEClassifiers() .get(602); } return ifcSlabEClass; }
java
@Override public void traverse(TraversalListener listener) { for (String classname: m_Classnames) listener.traversing(classname, null); }
java
public void setAttributeValues(java.util.Collection<String> attributeValues) { if (attributeValues == null) { this.attributeValues = null; return; } this.attributeValues = new com.amazonaws.internal.SdkInternalList<String>(attributeValues); }
java
public void marshall(BonusPayment bonusPayment, ProtocolMarshaller protocolMarshaller) { if (bonusPayment == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(bonusPayment.getWorkerId(), WORKERID_BINDIN...
python
def mux(index, *mux_ins, **kwargs): """ Multiplexer returning the value of the wire in . :param WireVector index: used as the select input to the multiplexer :param WireVector mux_ins: additional WireVector arguments selected when select>1 :param WireVector kwargs: additional WireVectors, keyword arg "...
java
public <R> StreamEx<R> flatMapKeyValue(BiFunction<? super K, ? super V, ? extends Stream<? extends R>> mapper) { return this.<R> flatMap(toFunction(mapper)); }
python
def skip_signatures_and_duplicates_concat_well_known_metadata(cls, default_dup_action=None, additional_rules=None): """Produces a rule set useful in many deploy jar creation contexts. The rule set skips duplicate entries by default, retaining the ...
java
public final ListAlertPoliciesPagedResponse listAlertPolicies(ProjectName name) { ListAlertPoliciesRequest request = ListAlertPoliciesRequest.newBuilder() .setName(name == null ? null : name.toString()) .build(); return listAlertPolicies(request); }
java
public int getNumberOfColumns() { List<WebElement> cells; String xPath = getXPathBase() + "tr"; List<WebElement> elements = HtmlElementUtils.locateElements(xPath); if (elements.size() > 0 && getDataStartIndex() - 1 < elements.size()) { cells = elements.get(getDataStartIndex...
python
def is_ignored(mod_or_pkg, ignored_package): """Test, if this :class:`docfly.pkg.picage.Module` or :class:`docfly.pkg.picage.Package` should be included to generate API reference document. :param mod_or_pkg: module or package :param ignored_package: ignored package **中文文档** 根据全名判断一个包或者模块是...
java
public void append(DigitBuffer other) { check(other.size); System.arraycopy(other.buf, 0, buf, size, other.size); size += other.size; }
java
public static List<Boolean> unmodifiableView(boolean[] array, int length) { return Collections.unmodifiableList(view(array, length)); }
java
public ArrayList<File> scanAllFiles(File directoryToScan) { CumulativeFileScannerObserver fileScanner = new CumulativeFileScannerObserver(); DirectoryScanner directoryScanner = new DirectoryScanner(fileScanner); for (FileScannerObserver fileScannerObserver : fileScanners) { directoryScanner.addFileScanner(f...
python
def timer(): """ Timer used for calculate time elapsed """ if sys.platform == "win32": default_timer = time.clock else: default_timer = time.time return default_timer()
python
def _find_files(self, entries, root, relative_path, file_name_regex): """ Return the elements in entries that 1. are in ``root/relative_path``, and 2. match ``file_name_regex``. :param list entries: the list of entries (file paths) in the container :param string root: t...
java
@Override public void reset(IoSession session) { synchronized (lock) { if (!ready && this.session != null) { throw new IllegalStateException("Cannot reset a future that has not yet completed"); } this.session = session; this.firstListener = nu...
java
public static String charToEscape(char ch) { String hexValue = Integer.toHexString(ch); if (hexValue.length() == 1) { return "\\u000" + hexValue; } if (hexValue.length() == 2) { return "\\u00" + hexValue; } if (hexValue.length() == 3) { ...
java
private static boolean polylineContainsPoint_(Polyline polyline_a, Point point_b, double tolerance, ProgressTracker progress_tracker) { // Quick rasterize test to see whether the the geometries are disjoint. if (tryRasterizedContainsOrDisjoint_(polyline_a, point_b, tolerance, false) == Relation.disjoint) ...
python
def _get_package_data(): """Iterate over the `init` dir for directories and returns all files within them. Only files within `binaries` and `templates` will be added. """ from os import listdir as ls from os.path import join as jn x = 'init' b = jn('serv', x) dr = ['binaries', 'tem...
java
public ArrayList<net.minidev.ovh.api.me.consumption.OvhTransaction> consumption_usage_forecast_GET() throws IOException { String qPath = "/me/consumption/usage/forecast"; StringBuilder sb = path(qPath); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t7); }
java
public static String serviceName(Class<?> serviceInterface) { // Service name Service serviceAnnotation = serviceInterface.getAnnotation(Service.class); if (serviceAnnotation == null) { throw new IllegalArgumentException( String.format("Not a service interface: %s", serviceInterface)); }...
java
public static String getFieldNameWithJavaCase(final String name) { return name==null?null:Character.toLowerCase(name.charAt(0))+name.substring(1); }
python
def get_conn(host='', username=None, password=None, port=445): ''' Get an SMB connection ''' if HAS_IMPACKET and not HAS_SMBPROTOCOL: salt.utils.versions.warn_until( 'Sodium', 'Support of impacket has been depricated and will be ' 'removed in Sodium. Please in...
java
private static boolean disjoint_(String scl) { if (scl.charAt(0) == 'F' && scl.charAt(1) == 'F' && scl.charAt(2) == '*' && scl.charAt(3) == 'F' && scl.charAt(4) == 'F' && scl.charAt(5) == '*' && scl.charAt(6) == '*' && scl.charAt(7) == '*' && scl.charAt(8) == '*') return true; return false; }
java
public static RgbaColor fromHsla(String hsl) { String[] parts = getHslaParts(hsl).split(","); if (parts.length == 4) { float[] HSL = new float[] { parseInt(parts[0]), parseInt(parts[1]), parseInt(parts[2]) }; RgbaColor ret = fromHsl(HSL); if (ret != null) { ...
java
public static int toInteger(final Boolean bool, final int trueValue, final int falseValue, final int nullValue) { if (bool == null) { return nullValue; } return bool.booleanValue() ? trueValue : falseValue; }
java
@Override public final StringBuilder renderAsListItem(final StringBuilder builder, final boolean newLine, final int pad) { GedRenderer.renderPad(builder, pad, newLine); builder.append(getListItemContents()); return builder; }
python
def rss_parse(self, response): """ Extracts all article links and initiates crawling them. :param obj response: The scrapy response """ for item in response.xpath('//item'): for url in item.xpath('link/text()').extract(): yield scrapy.Request(url, lam...
java
@Override public void searchMCS(boolean bondTypeMatch) { setBondMatchFlag(bondTypeMatch); searchVFMCSMappings(); boolean flag = mcgregorFlag(); if (flag && !vfLibSolutions.isEmpty()) { try { searchMcGregorMapping(); } catch (CDKException ex) { ...
java
public void holdCall( String connId, KeyValueCollection reasons, KeyValueCollection extensions ) throws WorkspaceApiException { try { VoicecallsidanswerData holdData = new VoicecallsidanswerData(); holdData.setReasons(Util.toKVList(reasons))...
java
@Override public int compareTo(LocationWhereValueBecomesNull o) { int cmp = this.location.compareTo(o.location); if (cmp != 0) { return cmp; } cmp = this.valueNumber.compareTo(o.valueNumber); return cmp; }
java
public static <T> Optional<T> tryFind(Iterator<T> iterator, Predicate<? super T> predicate) { UnmodifiableIterator<T> filteredIterator = filter(iterator, predicate); return filteredIterator.hasNext() ? Optional.of(filteredIterator.next()) : Optional.<T>absent(); }
java
public static void main(String[] args) { Tree t; try { t = Tree.valueOf("(S (NP (NNP Sam)) (VP (VBD died) (NP-TMP (NN today))))"); } catch (Exception e) { System.err.println("Horrible error: " + e); e.printStackTrace(); return; } t.pennPrint(); System.out.pr...
python
def sdb_get_or_set_hash(uri, opts, length=8, chars='abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)', utils=None): ''' Check if value exists in sdb. If it does, return, otherwise generate a random string and ...
python
def execute(self): """ Entry point to the execution of the program. """ # Ensure that we have commands registered if not self.commands or self._parser is None: raise NotImplementedError( "No commands registered with this program!" ) ...
python
def toNumber (str, default=None): """toNumber(str[, default]) -> integer | float | default Converts the given string to a numeric value. The string may be a hexadecimal, integer, or floating number. If string could not be converted, default (None) is returned. Examples: >>> n = toNumber("0x...
python
def separate_camel_case(word, first_cap_re, all_cap_re): """ What it says on the tin. Input: - word: A string that may be in camelCase. Output: - separated_word: A list of strings with camel case separated. """ s1 = first_cap_re.sub(r'\1 \2', word) separated_word = all_cap_re.sub(r'\1 \2'...
python
def changebase(string, frm, to, minlen=0): """ Change a string's characters from one base to another. Return the re-encoded string """ if frm == to: return lpad(string, get_code_string(frm)[0], minlen) return encode(decode(string, frm), to, minlen)
java
public static List<CPRule> filterFindByGroupId(long groupId, int start, int end) { return getPersistence().filterFindByGroupId(groupId, start, end); }
python
def get_driver_payments(self, offset=None, limit=None, from_time=None, to_time=None ): """Get payments about the authorized Uber driver. Parameters off...
java
private static void init() { if (alFirstConsonants == null) { alFirstConsonants = new ArrayList(); alLastConsonants = new ArrayList(); alMainVowels = new ArrayList(); alSecondaryVowels = new ArrayList(); initArrayList(alFirstConsonants, vnFirstConsonants); initArrayList(alLastConsonants, vnLastCons...
python
def compare(args): """ Compare the extant river with the given name to the passed JSON. The command will exit with a return code of 0 if the named river is configured as specified, and 1 otherwise. """ data = json.load(sys.stdin) m = RiverManager(args.hosts) if m.compare(args.name, data)...
python
def write_separated_lines(path, values, separator=' ', sort_by_column=0): """ Writes list or dict to file line by line. Dict can have list as value then they written separated on the line. Parameters: path (str): Path to write file to. values (dict, list): A dictionary or a list to writ...
python
def next_occurrences(self, n=None, since=None): """Yield the next planned occurrences after the date "since" The `since` argument can be either a date or datetime onject. If not given, it defaults to the date of the last event that's already planned. If `n` is given, the result...
java
public ApiResponse<DeviceTaskUpdateResponse> updateTaskForDeviceWithHttpInfo(String tid, String did, DeviceTaskUpdateRequest deviceTaskUpdateRequest) throws ApiException { com.squareup.okhttp.Call call = updateTaskForDeviceValidateBeforeCall(tid, did, deviceTaskUpdateRequest, null, null); Type localVarR...
java
protected String getMessageInternal(Locale locale, String code, Object[] args) { if(code == null) { return null; } if(locale == null) { locale = I18nUtils.getLocale(); } final MessageFormat messageFormat = resolveMessageFormat(locale, code); if(messageFormat != null) { synchronized(messageFormat)...
python
def t_seg(p1, p2, t, align=0): """ trim segment Args: p1, p2: point(x, y) t: scaling factor (1 - trimed segment / original segment) align: 1: trim p2, 2: trim p1, 0: both side Return: trimmed segment(p1, p2) """ v = vector(p1, p2) result = { 1: lambda a, b: (a, tr...
java
@Override public void connectionRecovered(IManagedConnectionEvent<C> event) { // physical connection is already set free if (!event.getManagedConnection().hasCoreConnection()) { return; } IPhynixxConnection con = event.getManagedConnection() .getCoreConnection(); if (con == null || !(con instanceof IX...
java
public boolean isCompatibleWith(DataType other) { // A type is compatible with a choice type if it is a subtype of one of the choice types if (other instanceof ChoiceType) { for (DataType choice : ((ChoiceType)other).getTypes()) { if (this.isSubTypeOf(choice)) { ...
python
def integral(requestContext, seriesList): """ This will show the sum over time, sort of like a continuous addition function. Useful for finding totals or trends in metrics that are collected per minute. Example:: &target=integral(company.sales.perMinute) This would start at zero on th...
python
def load(input_stream=None): """ Load JSON-encoded document and return a :class:`.Doc` element. The JSON input will be read from :data:`sys.stdin` unless an alternative text stream is given (a file handle). To load from a file, you can do: >>> import panflute as pf >>> with open('...
java
public EList<Boolean> getValues() { if (values == null) { values = new EDataTypeEList<Boolean>(Boolean.class, this, TypesPackage.JVM_BOOLEAN_ANNOTATION_VALUE__VALUES); } return values; }
java
public void setContentAddStyleNames(String value) { if (value == null || value.isEmpty()) return; JQMCommon.addStyleNames(content, value); }
python
def flush(self): """Ensure contents are written to file.""" for name in self.item_names: item = self[name] item.flush() self.file.flush()
java
public XAttributeTimestamp createAttributeTimestamp(String key, Date value, XExtension extension) { return new XAttributeTimestampImpl(intern(key), value, extension); }
python
def forward_backward(self, x): """Perform forward and backward computation for a batch of src seq and dst seq""" (src_seq, tgt_seq, src_valid_length, tgt_valid_length), batch_size = x with mx.autograd.record(): out, _ = self._model(src_seq, tgt_seq[:, :-1], ...
python
def create_future(loop): # pragma: no cover """Compatibility wrapper for the loop.create_future() call introduced in 3.5.2.""" if hasattr(loop, 'create_future'): return loop.create_future() return asyncio.Future(loop=loop)
python
def get_usage_string(self): """Returns usage representation string (as embedded in HID device if available) """ if self.string_index: usage_string_type = c_wchar * MAX_HID_STRING_LENGTH # 128 max string length abuffer = usage_string_type() ...
java
void preBackout(Transaction transaction) throws ObjectManagerException { throw new InvalidStateException(this, InternalTransaction.stateTerminated, InternalTransaction.stateNames[InternalTransaction.stateTerminated]); }
java
private static String getKey(Object... objects) { Object[] args = new Object[objects.length + 1]; args[0] = LineageEventBuilder.LIENAGE_EVENT_NAMESPACE; System.arraycopy(objects, 0, args, 1, objects.length); return LineageEventBuilder.getKey(args); }
java
public static boolean[] removeAllOccurrences(final boolean[] a, final boolean element) { if (N.isNullOrEmpty(a)) { return N.EMPTY_BOOLEAN_ARRAY; } final boolean[] copy = a.clone(); int idx = 0; for (int i = 0, len = a.length; i < len; i++) { if ...
java
public static String escapeShell(final String s) { if(null==s){ return s; } if (s.startsWith("'") && s.endsWith("'")) { return s; } else if (s.startsWith("\"") && s.endsWith("\"")) { return s.replaceAll("([\\\\`])", "\\\\$1"); } return ...
java
public static String getParameter(final PageParameters parameters, final String name) { return getString(parameters.get(name)); }
python
def select_one_album(albums): """Display the albums returned by search api. :params albums: API['result']['albums'] :return: a Album object. """ if len(albums) == 1: select_i = 0 else: table = PrettyTable(['Sequence', 'Album Name', 'Artist Name']...
java
public final void add(ByteBuf buf, ChannelFutureListener listener) { // buffers are added before promises so that we naturally 'consume' the entire buffer during removal // before we complete it's promise. bufAndListenerPairs.add(buf); if (listener != null) { bufAndListenerPa...
java
@SuppressWarnings("unchecked") public static <T extends Executable> T getRootExecutable(T m) { return (T) EXECUTABLE_GET_ROOT.apply(m); }
java
public static <T> T[] validIndex(final T[] array, final int index, final String message, final Object... values) { Validate.notNull(array); if (index < 0 || index >= array.length) { throw new IndexOutOfBoundsException(StringUtils.simpleFormat(message, values)); } return array...
python
def add_colorbar(self, **kwargs): """Draw a colorbar """ kwargs = kwargs.copy() if self._cmap_extend is not None: kwargs.setdefault('extend', self._cmap_extend) if 'label' not in kwargs: kwargs.setdefault('label', label_from_attrs(self.data)) self....
python
def _get_atomic_dtype(data_type): """Retrieve the NumPy's `dtype` for a given atomic data type.""" atomic_type = getattr(data_type, 'type', None) if atomic_type is not None: return atomic_type return _PREDEFINED_ATOMIC_NUMPY_TYPES[_find_base_type(data_type)]
java
public String getTableNames(boolean bAddQuotes) { return (m_tableName == null) ? Record.formatTableNames(ANALYSIS_LOG_FILE, bAddQuotes) : super.getTableNames(bAddQuotes); }
java
public PooledConnection getPooledConnection(String user, String password) throws SQLException { return new MariaDbPooledConnection((MariaDbConnection) getConnection(user, password)); }
java
@Override public void snapshot(String snapshotName, TableName tableName, SnapshotType arg2) throws IOException, SnapshotCreationException, IllegalArgumentException { snapshot(snapshotName, tableName); }
java
public static Result run(String inPaths, String pkgName, String outPath, boolean dbg, boolean vbs) throws IOException, ClassHierarchyException, IllegalArgumentException { DEBUG = dbg; VERBOSE = vbs; long start = System.currentTimeMillis(); Set<String> setInPaths = new HashSet<>(Arrays.asList(inPat...
java
private void printText(PrintWriter pw, String key, String defaultText) { String text = null; if (key != null) { ResourceBundle bundle = null; // retrieve the resource bundle try { bundle = ResourceBundle.getBundle(DIST_EX_RESOURCE_BUNDLE_NAME); ...
java
public void marshall(ResourceQuery resourceQuery, ProtocolMarshaller protocolMarshaller) { if (resourceQuery == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(resourceQuery.getType(), TYPE_BINDING); ...
python
def ngram_counts(args, parser): """Outputs the results of performing a counts query.""" store = utils.get_data_store(args) corpus = utils.get_corpus(args) catalogue = utils.get_catalogue(args) store.validate(corpus, catalogue) store.counts(catalogue, sys.stdout)
java
protected Boolean _hasSideEffects(XReturnExpression expression, ISideEffectContext context) { return hasSideEffects(expression.getExpression(), context); }