language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def _init_parameters_random(self, X_bin): """Initialise parameters for unsupervised learning. """ _, n_features = X_bin.shape # The parameter class_log_prior_ has shape (2,). The values represent # 'match' and 'non-match'. rand_vals = np.random.rand(2) class_pr...
python
def maybe_show_tree(walker, ast): """ Show the ast based on the showast flag (or file object), writing to the appropriate stream depending on the type of the flag. :param show_tree: Flag which determines whether the parse tree is written to sys.stdout or not. (It is also to pass a...
java
public static String toFullJobPath(final String jobName) { final String[] parts = jobName.split("/"); if (parts.length == 1) return parts[0]; final StringBuilder sb = new StringBuilder(DEFAULT_BUFFER_SIZE); for (int i = 0; i < parts.length; i++) { sb.append(parts[i])...
python
def queue_delete(self, queue, if_unused=False, if_empty=False): """Delete queue by name.""" return self.channel.queue_delete(queue, if_unused, if_empty)
java
public static Intent createUriIntent(String intentAction, String intentUri) { if (intentAction == null) { intentAction = Intent.ACTION_VIEW; } return new Intent(intentAction, Uri.parse(intentUri)) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_REORDER_...
python
def predict_mean_and_var(self, Fmu, Fvar, epsilon=None): r""" Given a Normal distribution for the latent function, return the mean of Y if q(f) = N(Fmu, Fvar) and this object represents p(y|f) then this method computes the predictive mean ...
python
def get_balance(self, t: datetime): """ Returns account balance before specified datetime (excluding entries on the datetime). :param t: datetime :return: Decimal """ return sum_queryset(self.accountentry_set.all().filter(timestamp__lt=t))
python
def find_lexer_class_by_name(_alias): """Lookup a lexer class by alias. Like `get_lexer_by_name`, but does not instantiate the class. .. versionadded:: 2.2 """ if not _alias: raise ClassNotFound('no lexer for alias %r found' % _alias) # lookup builtin lexers for module_name, name, ...
python
def create_app(self): """Send a POST to spinnaker to create a new application with class variables. Raises: AssertionError: Application creation failed. """ self.appinfo['accounts'] = self.get_accounts() self.log.debug('Pipeline Config\n%s', pformat(self.pipeline_con...
java
public final hqlParser.bitwiseAndExpression_return bitwiseAndExpression() throws RecognitionException { hqlParser.bitwiseAndExpression_return retval = new hqlParser.bitwiseAndExpression_return(); retval.start = input.LT(1); CommonTree root_0 = null; Token BAND197=null; ParserRuleReturnScope additiveExpressi...
python
def execute(self, *args, **options): """ Executes whole process of parsing arguments, running command and trying to catch errors. """ try: self.handle(*args, **options) except CommandError, e: if options['debug']: try: ...
java
public void setParent( IVarDef parent) { super.setParent( parent); // Reset ancestry for all descendants. if( members_ != null) { for( IVarDef member : members_) { member.setParent( this); } } }
python
def getNextContextStack(self, contextStack, data=None): """Apply modification to the contextStack. This method never modifies input parameter list """ if self._popsCount: contextStack = contextStack.pop(self._popsCount) if self._contextToSwitch is not None: ...
python
def from_row_and_group(row: int, group: int): """ Returns an element from a row and group number. Args: row (int): Row number group (int): Group number .. note:: The 18 group number system is used, i.e., Noble gases are group 18. """ ...
python
def token(self): """ :rtype: str """ if self._session_context is not None: return self.session_context.token elif self._installation_context is not None: return self.installation_context.token else: return None
python
def determine_types(self): """ Determine ES type names from request data. In particular `request.matchdict['collections']` is used to determine types names. Its value is comma-separated sequence of collection names under which views have been registered. """ from neferta...
python
def get_stp_mst_detail_output_msti_port_designated_port_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_stp_mst_detail = ET.Element("get_stp_mst_detail") config = get_stp_mst_detail output = ET.SubElement(get_stp_mst_detail, "output") ...
python
def check_process_counts(self): """Check for the minimum consumer process levels and start up new processes needed. """ LOGGER.debug('Checking minimum consumer process levels') for name in self.consumers: processes_needed = self.process_spawn_qty(name) if...
python
def authors(): """ Updates the AUTHORS file with a list of committers from GIT. """ fmt_re = re.compile(r'([^<]+) <([^>]+)>') authors = local('git shortlog -s -e -n | cut -f 2-', capture=True) with open('AUTHORS', 'w') as fh: fh.write('Project contributors\n') fh.write('=========...
python
def platform_default(): """Return the platform string for our execution environment. The returned value should map to one of the SCons/Platform/*.py files. Since we're architecture independent, though, we don't care about the machine architecture. """ osname = os.name if osname == 'java': ...
java
public static Object[] appendArray(Object[] arr, Object obj) { Object[] newArr = new Object[arr.length + 1]; System.arraycopy(arr, 0, newArr, 0, arr.length); newArr[arr.length] = obj; return newArr; }
python
def check_config_integrity(self): """ Make sure the scheduler config is valid """ tasks_by_hash = {_hash_task(t): t for t in self.config_tasks} if len(tasks_by_hash) != len(self.config_tasks): raise Exception("Fatal error: there was a hash duplicate in the scheduled tasks config.") ...
python
def write_psd(self, psds, group=None): """Writes PSD for each IFO to file. Parameters ----------- psds : {dict, FrequencySeries} A dict of FrequencySeries where the key is the IFO. group : {None, str} The group to write the psd to. Default is ``data_group...
python
def connect(self, funct): """Call funct when the text was changed. Parameters ---------- funct : function function that broadcasts a change. Notes ----- There is something wrong here. When you run this function, it calls for opening a directo...
python
def reload(self, reload_timeout=300, save_config=True): """Reload the device and waits for device to boot up. It posts the informational message to the log if not implemented by device driver. """ self.log("Reload not implemented on {} platform".format(self.platform))
java
@Override public ZeroCopyFileWriter write(String event) { // String realPath = FileHandlerUtil.generateOutputFilePath(path); String realPath = FileHandlerUtil.generateOutputFilePath( path, FileHandlerUtil.generateAuditFileName()); try { /** Close last instance for ...
java
public PythonDataStream from_collection(Iterator<Object> iter) throws Exception { return new PythonDataStream<>(env.addSource(new PythonIteratorFunction(iter), TypeExtractor.getForClass(Object.class)) .map(new AdapterMap<>())); }
java
public CountDownLatch routeChat() { info("*** RouteChat"); final CountDownLatch finishLatch = new CountDownLatch(1); StreamObserver<RouteNote> requestObserver = asyncStub.routeChat(new StreamObserver<RouteNote>() { @Override public void onNext(RouteNote note) { info("...
java
public boolean accountSupportsFeatures(Collection<? extends CharSequence> features) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { EntityBareJid accountJid = connection().getUser().asEntityBareJid(); return supportsFeatures(accountJid, f...
python
def restart(self, timeout=300, config_callback=None): """Restart each member of the replica set.""" for member_id in self.server_map: host = self.server_map[member_id] server_id = self._servers.host_to_server_id(host) server = self._servers._storage[server_id] ...
python
def Union(self, t2, off): """Union initializes any Table-derived type to point to the union at the given offset.""" assert type(t2) is Table N.enforce_number(off, N.UOffsetTFlags) off += self.Pos t2.Pos = off + self.Get(N.UOffsetTFlags, off) t2.Bytes = self.By...
python
def wb010(self, value=None): """ Corresponds to IDD Field `wb010` Wet-bulb temperature corresponding to 1.0% annual cumulative frequency of occurrence Args: value (float): value for IDD Field `wb010` Unit: C if `value` is None it will not be checked ...
java
@Override public List<CommerceSubscriptionEntry> findByG_U(long groupId, long userId) { return findByG_U(groupId, userId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); }
python
def API_GET(self, courseid, taskid, submissionid): # pylint: disable=arguments-differ """ List all the submissions that the connected user made. Returns list of the form :: [ { "id": "submission_id1", ...
java
public static void mergePdf(File[] inputPdfFiles, File outputPdfFile) { //get Ghostscript instance Ghostscript gs = Ghostscript.getInstance(); //prepare Ghostscript interpreter parameters //refer to Ghostscript documentation for parameter usage //gs -sDEVICE=pdfwrite -dNOP...
java
public Tile tile (float x, float y, float width, float height) { final float tileX = x, tileY = y, tileWidth = width, tileHeight = height; return new Tile() { @Override public Texture texture () { return Texture.this; } @Override public float width () { return tileWidth; } @Override public flo...
java
@VisibleForTesting static int getNextAvailablePort(InetAddress address, PortAllocator portAllocator) { for (int i = 0; i < PORT_MAX_TRIES; i++) { int port = portAllocator.getAvailable(address); if (isValidPort(port)) { PORTS_ALREADY_ALLOCATED.add(port); return port; } } t...
python
def decorator(caller, func=None): """ decorator(caller) converts a caller function into a decorator; decorator(caller, func) decorates a function using a caller. """ if func is None: # returns a decorator fun = FunctionMaker(caller) first_arg = inspect.getargspec(caller)[0][0] ...
python
def create_example(self, workspace_id, intent, text, mentions=None, **kwargs): """ Create user input example. Add a new user input example to an intent. This operation is l...
java
@Throws(IllegalNaNArgumentException.class) public static double notNaN(final double value, @Nullable final String name) { // most efficient check for NaN, see Double.isNaN(value)) if (value != value) { throw new IllegalNaNArgumentException(name); } return value; }
java
public Response remove(Object object) { assertNotEmpty(object, "object"); JsonObject jsonObject = getGson().toJsonTree(object).getAsJsonObject(); final String id = getAsString(jsonObject, "_id"); final String rev = getAsString(jsonObject, "_rev"); return remove(id, rev); }
java
public DeleteNotificationResponse deleteNotification(DeleteNotificationRequest request) { checkNotNull(request, "The parameter request should NOT be null."); checkStringNotEmpty(request.getName(), "The parameter name should NOT be null or empty string."); InternalRequest internalRequest = create...
java
public OperationFuture<AlertPolicy> delete(AlertPolicy policyRef) { client.deleteAlertPolicy(findByRef(policyRef).getId()); return new OperationFuture<>( policyRef, new NoWaitingJobFuture() ); }
python
def wrap_many(self, *args, strict=False): """Wraps different copies of this element inside all empty tags listed in params or param's (non-empty) iterators. Returns list of copies of this element wrapped inside args or None if not succeeded, in the same order and same structure, ...
java
public Observable<VpnClientIPsecParametersInner> setVpnclientIpsecParametersAsync(String resourceGroupName, String virtualNetworkGatewayName, VpnClientIPsecParametersInner vpnclientIpsecParams) { return setVpnclientIpsecParametersWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayName, vpnclientIp...
java
public void push (final T newVal) { final int index = (int) (m_aCurrentIndex.incrementAndGet () % m_nMaxSize); m_aCircularArray[index].set (newVal); }
java
private void flushBuffer(ByteBuffer buffer, WritableByteChannel output) throws IOException { buffer.flip(); output.write(buffer); buffer.flip(); buffer.limit(buffer.capacity()); }
java
@Override protected void replaceEditor(JComponent oldEditor, JComponent newEditor) { spinner.remove(oldEditor); spinner.add(newEditor, "Editor"); if (oldEditor instanceof JSpinner.DefaultEditor) { JTextField tf = ((JSpinner.DefaultEditor)oldEditor).getTextField(); ...
java
@Override public void paint(final RenderContext renderContext) { boolean enabled = ConfigurationProperties.getWhitespaceFilter(); if (enabled && renderContext instanceof WebXmlRenderContext) { PrintWriter writer = ((WebXmlRenderContext) renderContext).getWriter(); writer = new WhiteSpaceFilterPrintWriter(wr...
java
public <T> CompletableFuture<T> traceAsync(final Class<T> type, final Consumer<HttpConfig> configuration) { return CompletableFuture.supplyAsync(() -> trace(type, configuration), getExecutor()); }
java
public <T> LazyCursorList<T> toLazyCursorList(Function<? super Cursor, T> singleRowTransform) { return new LazyCursorList<>(this, singleRowTransform); }
python
def assert_regex(text, regex, msg_fmt="{msg}"): """Fail if text does not match the regular expression. regex can be either a regular expression string or a compiled regular expression object. >>> assert_regex("Hello World!", r"llo.*rld!$") >>> assert_regex("Hello World!", r"\\d") Traceback (mo...
python
def etd_ms_dict2xmlfile(filename, metadata_dict): """Create an ETD MS XML file.""" try: f = open(filename, 'w') f.write(generate_etd_ms_xml(metadata_dict).encode("utf-8")) f.close() except: raise MetadataGeneratorException( 'Failed to create an XML file. Filename:...
java
public Observable<Page<VirtualNetworkPeeringInner>> listAsync(final String resourceGroupName, final String virtualNetworkName) { return listWithServiceResponseAsync(resourceGroupName, virtualNetworkName) .map(new Func1<ServiceResponse<Page<VirtualNetworkPeeringInner>>, Page<VirtualNetworkPeeringInne...
python
def derive_resource_name(name): """A stable, human-readable name and identifier for a resource.""" if name.startswith("Anon"): name = name[4:] if name.endswith("Handler"): name = name[:-7] if name == "Maas": name = "MAAS" return name
java
public static int floatToIntBits(float value) { int result = floatToRawIntBits(value); // Check for NaN based on values of bit fields, maximum // exponent and nonzero significand. if ( ((result & FloatConsts.EXP_BIT_MASK) == FloatConsts.EXP_BIT_MASK) && (result...
python
def objname(self, obj=None): """ Formats object names in a pretty fashion """ obj = obj or self.obj _objname = self.pretty_objname(obj, color=None) _objname = "'{}'".format(colorize(_objname, "blue")) return _objname
python
def update_title(self, title): """Renames the worksheet. :param title: A new title. :type title: str """ body = { 'requests': [{ 'updateSheetProperties': { 'properties': { 'sheetId': self.id, ...
java
public static <P extends Enum<P>> PointF optPointF(final JSONObject json, P e) { return optPointF(json, e, null); }
python
def bit_flip_operators(p): """ Return the phase flip kraus operators """ k0 = np.sqrt(1 - p) * I k1 = np.sqrt(p) * X return k0, k1
python
def clone_surface(self, source_name, target_name, target_position=-1, alpha=1.): ''' Clone surface from existing layer to a new name, inserting new surface at specified position. By default, new surface is appended as the top surface layer. Args --...
python
def password_attributes_min_length(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") password_attributes = ET.SubElement(config, "password-attributes", xmlns="urn:brocade.com:mgmt:brocade-aaa") min_length = ET.SubElement(password_attributes, "min-length") ...
java
public HBCIMsgStatus rawDoIt(Message message, boolean signit, boolean cryptit) { HBCIMsgStatus msgStatus = new HBCIMsgStatus(); try { message.complete(); log.debug("generating raw message " + message.getName()); passport.getCallback().status(HBCICallback.STATUS_MSG_...
python
def ns_whois(self, nameservers, limit=DEFAULT_LIMIT, offset=DEFAULT_OFFSET, sort_field=DEFAULT_SORT): '''Gets the domains that have been registered with a nameserver or nameservers''' if not isinstance(nameservers, list): uri = self._uris["whois_ns"].format(nameservers) p...
python
def get_memory_layout(device): """Returns an array which identifies the memory layout. Each entry of the array will contain a dictionary with the following keys: addr - Address of this memory segment last_addr - Last address contained within the memory segment. size - siz...
python
def sort_args(args): """Put flags at the end""" args = args.copy() flags = [i for i in args if FLAGS_RE.match(i[1])] for i in flags: args.remove(i) return args + flags
java
public Client getClient() throws Exception { ClientConfig config = new ClientConfig(); // turn off the timeout for debugging config.setProcedureCallTimeout(0); Client client = ClientFactory.createClient(config); // track this client so it can be closed at shutdown tracked...
java
protected void addCustomBindings(final DocWorkUnit currentWorkUnit) { final String tagFilterPrefix = getTagPrefix(); Arrays.stream(currentWorkUnit.getClassDoc().inlineTags()) .filter(t -> t.name().startsWith(tagFilterPrefix)) .forEach(t -> currentWorkUnit.setProperty(t.na...
java
public static HtmlTree HTML(String lang, Content head, Content body) { HtmlTree htmltree = new HtmlTree(HtmlTag.HTML, nullCheck(head), nullCheck(body)); htmltree.addAttr(HtmlAttr.LANG, nullCheck(lang)); return htmltree; }
java
public static <T> T fromJSON(String json, Class<T> classOfT) { return gson.fromJson(json, classOfT); }
python
def _sample_point(self, sample=None): """ Returns a dict that represents the sample point assigned to the sample specified Keys: obj, id, title, url """ samplepoint = sample.getSamplePoint() if sample else None data = {} if samplepoint: data = ...
python
def sample(self, n=None, frac=None, replace=False, weights=None, random_state=None, axis=None): """ Return a random sample of items from an axis of object. You can use `random_state` for reproducibility. Parameters ---------- n : int, optional ...
java
public static Schema fieldSchema(Schema schema, PartitionStrategy strategy, String name) { if (strategy != null && Accessor.getDefault().hasPartitioner(strategy, name)) { return partitionFieldSchema(Accessor.getDefault().getPartitioner(strategy, name), schema); ...
java
public final Promise get(String key) { byte[] binaryKey = key.getBytes(StandardCharsets.UTF_8); if (client != null) { return new Promise(client.get(binaryKey)); } if (clusteredClient != null) { return new Promise(clusteredClient.get(binaryKey)); } return Promise.resolve(); }
java
public Set<String> setEscapeJava(final Set<?> target) { if (target == null) { return null; } final Set<String> result = new LinkedHashSet<String>(target.size() + 2); for (final Object element : target) { result.add(escapeJava(element)); } return re...
java
@Override public Cursor runQueryOnBackgroundThread(CharSequence constraint) { if (DBG) Log.d(LOG_TAG, "runQueryOnBackgroundThread(" + constraint + ")"); String query = (constraint == null) ? "" : constraint.toString(); /** * for in app search we show the progress spinner until the c...
java
int getFirstChar(int category) { RangeDescriptor rlRange; int retVal = -1; for (rlRange = fRangeList; rlRange!=null; rlRange=rlRange.fNext) { if (rlRange.fNum == category) { retVal = rlRange.fStartChar; break; } } ...
java
Rule XcomStaffbreak() { return Sequence("staffbreak", OneOrMore(WSP()).suppressNode(), XcomNumber(), XcomUnit()) .label(XcomStaffbreak); }
python
def load_ui_type(uifile): """Pyside equivalent for the loadUiType function in PyQt. From the PyQt4 documentation: Load a Qt Designer .ui file and return a tuple of the generated form class and the Qt base class. These can then be used to create any number of instances of the user interf...
java
@Nullable private String getPastTenseVerbSuggestion(String word) { if (word.endsWith("e")) { // strip trailing "e" String wordStem = word.substring(0, word.length()-1); try { String lemma = baseForThirdPersonSingularVerb(wordStem); if (lemma != null) { AnalyzedToken tok...
python
def get_stp_mst_detail_output_cist_port_edge_delay(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_stp_mst_detail = ET.Element("get_stp_mst_detail") config = get_stp_mst_detail output = ET.SubElement(get_stp_mst_detail, "output") cist...
java
protected void doUpdate(final ItemData item, final WorkspaceStorageConnection con, ChangedSizeHandler sizeHandler) throws RepositoryException, InvalidItemStateException { if (item.isNode()) { con.update((NodeData)item); } else { con.update((PropertyData)item, si...
python
def setCurrentIndex(self, y, x): """Set current selection.""" self.dataTable.selectionModel().setCurrentIndex( self.dataTable.model().index(y, x), QItemSelectionModel.ClearAndSelect)
python
def wheel(self, direction, steps): """ Clicks the wheel the specified number of steps in the given direction. Use Mouse.WHEEL_DOWN, Mouse.WHEEL_UP """ self._lock.acquire() if direction == 1: wheel_moved = steps elif direction == 0: wheel_moved = -...
java
public static OMMapManager getInstance() { if (instanceRef.get() == null) { synchronized (instanceRef) { if (instanceRef.compareAndSet(null, createInstance())) { instanceRef.get().init(); } } } return instanceRef.get(); }
java
@Override public void recycle() { for (int i = first; i != last; i = next(i)) { bufs[i].recycle(); } first = last = 0; }
java
private static final String coerceToString(final Object obj) { if (obj == null) { return ""; } else if (obj instanceof String) { return (String) obj; } else if (obj instanceof Enum<?>) { return ((Enum<?>) obj).name(); } else { return obj.to...
java
public static <E> Iterator<E> takeWhile(Iterable<E> iterable, Predicate<E> predicate) { dbc.precondition(iterable != null, "cannot takeWhile from a null iterable"); return new TakeWhileIterator<E>(iterable.iterator(), predicate); }
python
def log_config(self): ''' Log the current logging configuration. ''' level = self.level debug = self.debug debug('Logging config:') debug('/ name: {}, id: {}', self.name, id(self)) debug(' .level: %s (%s)', level_map_int[level], level) debug(' .default_level: %s...
java
public int read(byte[] b, int off, int len) throws IOException { // Sanity checks ensureOpen(); if (b == null) { throw new NullPointerException("Null buffer for read"); } else if (off < 0 || len < 0 || len > b.length - off) { throw new IndexOutOfBoundsException();...
python
def decode_chain_list(in_bytes): """Convert a list of bytes to a list of strings. Each string is of length mmtf.CHAIN_LEN :param in_bytes: the input bytes :return the decoded list of strings""" tot_strings = len(in_bytes) // mmtf.utils.constants.CHAIN_LEN out_strings = [] for i in range(tot_str...
java
public static EquivalenceClasser<List<String>, String> typedDependencyClasser() { return new EquivalenceClasser<List<String>, String>() { public String equivalenceClass(List<String> s) { if(s.get(5).equals(leftHeaded)) return s.get(2) + '(' + s.get(3) + "->" + s.get(4) + ')'; re...
python
def get_option_pool(self, id_option_pool): """Search Option Pool by id. :param id_option_pool: Identifier of the Option Pool. Integer value and greater than zero. :return: Following dictionary: :: {‘id’: < id_option_pool >, ‘type’: < tipo_opcao >, ...
python
def get_category_lists(init_kwargs=None, additional_parents_aliases=None, obj=None): """Returns a list of CategoryList objects, optionally associated with a given model instance. :param dict|None init_kwargs: :param list|None additional_parents_aliases: :param Model|None obj: Model instance to get ...
java
@Trivial private static final String createSessionAttributeKey(String sessionId, String attributeId) { return new StringBuilder(sessionId.length() + 1 + attributeId.length()) .append(sessionId) .append('.') .append(attributeId) ...
java
private void allClustersEqual(final List<String> clusterUrls) { Validate.notEmpty(clusterUrls, "clusterUrls cannot be null"); // If only one clusterUrl return immediately if (clusterUrls.size() == 1) return; AdminClient adminClientLhs = adminClientPerCluster.get(clusterUrls.g...
python
def bed(args): """ %prog bed xmlfile Print summary of optical map alignment in BED format. """ from jcvi.formats.bed import sort p = OptionParser(bed.__doc__) p.add_option("--blockonly", default=False, action="store_true", help="Only print out large blocks, not fragments [...
java
private CmsResource getResource(CmsObject cms, String resourcename, CmsResourceFilter filter) throws CmsException { // the path without trailing slash String path = CmsResource.getParentFolder(resourcename); if (path == null) { return null; } // the parent path ...
java
public void load(InputStream input) throws IOException { ParameterReader reader = null; try { reader = new ParameterReader(new InputStreamReader(input, CmsEncoder.ENCODING_ISO_8859_1)); } catch (UnsupportedEncodingException ex) { reader = new ParameterReader(...
java
public void cookieMatches(double seconds, String cookieName, String expectedCookiePattern) { double end = System.currentTimeMillis() + (seconds * 1000); while (app.is().cookiePresent(cookieName) && System.currentTimeMillis() < end) ; if (app.is().cookiePresent(cookieName)) { while (!...