language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public <T> T executeWithTxUser(final String user, final SpecificUserAction<T> userAction) { final boolean userChanged = checkSpecificUserConditions(user); final ODatabaseDocument db = connectionProvider.get(); final T res; if (userChanged) { // this may cause security excepti...
java
public final ControlAckExpected createNewControlAckExpected() throws MessageCreateFailedException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "createNewControlAckExpected"); ControlAckExpected msg = null; try { msg = new ControlAckExpectedImpl(MfpConstants.CONSTR...
java
private void paintMinimizeHover(Graphics2D g, JComponent c, int width, int height) { iconifyPainter.paintHover(g, c, width, height); }
python
def _FormatHostname(self, event): """Formats the hostname. Args: event (EventObject): event. Returns: str: formatted hostname field. """ hostname = self._output_mediator.GetHostname(event) return self._FormatField(hostname)
java
public void getGuildPermissionInfo(String[] ids, Callback<List<GuildPermission>> callback) throws GuildWars2Exception, NullPointerException { isParamValid(new ParamChecker(ids)); gw2API.getGuildPermissionInfo(processIds(ids), GuildWars2.lang.getValue()).enqueue(callback); }
python
def _get_qtyprc(self, n_points=6): """ Returns a list of tuples of the form (qty, prc) created from the cost function. If the cost function is polynomial it will be converted to piece-wise linear using poly_to_pwl(n_points). """ if self.pcost_model == POLYNOMIAL: # C...
java
private void lockEvent(EventId eventId) { Lockable<V> eventWrapper = sharedBuffer.getEvent(eventId); checkState( eventWrapper != null, "Referring to non existent event with id %s", eventId); eventWrapper.lock(); sharedBuffer.upsertEvent(eventId, eventWrapper); }
java
private Set<Map.Entry<Object,Double>> entrySet(Set<Map.Entry<Object,Double>> s, Object[] key, boolean useLists) { if (depth == 1) { //System.out.println("key is long enough to add to set"); Set<K> keys = map.keySet(); for (K finalKey: keys) { // array doesn't escape K[] newKe...
python
def phi_s(spin1x, spin1y, spin2x, spin2y): """ Returns the sum of the in-plane perpendicular spins.""" phi1 = phi_from_spinx_spiny(spin1x, spin1y) phi2 = phi_from_spinx_spiny(spin2x, spin2y) return (phi1 + phi2) % (2 * numpy.pi)
python
def _parse_group(self, group_name, group): """ Parse a group definition from a dynamic inventory. These are top-level elements which are not '_meta(data)'. """ if type(group) == dict: # Example: # { # "mgmt": { # "...
java
static void requireState(boolean expression, String template, @Nullable Object... args) { if (!expression) { throw new IllegalStateException(String.format(template, args)); } }
python
def _stream_dat(file_name, pb_dir, byte_count, start_byte, dtype): """ Stream data from a remote dat file, into a 1d numpy array. Parameters ---------- file_name : str The name of the dat file to be read. pb_dir : str The physiobank directory where the dat file is located. b...
java
public double[][] initializeRanges() { if (m_Data == null) { m_Ranges = null; return m_Ranges; } int numAtt = m_Data.numAttributes(); double[][] ranges = new double [numAtt][3]; if (m_Data.numInstances() <= 0) { initializeRangesEmpty(numAtt, ranges); m_Ranges = rang...
java
public Receiver open(Receiver receiver)// throws IOException { this.receiver = receiver; Runtime rt = Runtime.getRuntime(); //command + arguments, environment parameters, workingdir try { proc = rt.exec(commandArray, null, workingDir); } catch (IOException e) { throw new RuntimeException("can not st...
python
def download_deviation(self, deviationid): """Get the original file download (if allowed) :param deviationid: The deviationid you want download info for """ response = self._req('/deviation/download/{}'.format(deviationid)) return { 'src' : response['src'], ...
python
def color_mix(img_spec1=None, img_spec2=None, alpha_channels=None, color_space='rgb', view_set=(0, 1, 2), num_slices=(10,), num_rows=2, rescale_method='global', background_threshold=0.05, annot=...
java
public static <K, V> LinkedHashMap<K, V> sortToMap(Collection<Map.Entry<K, V>> entryCollection, Comparator<Map.Entry<K, V>> comparator) { List<Map.Entry<K, V>> list = new LinkedList<>(entryCollection); Collections.sort(list, comparator); LinkedHashMap<K, V> result = new LinkedHashMap<>(); for (Map.Entry<K...
java
public ColorBuffer truncate(int len) { ColorBuffer cbuff = new ColorBuffer(useColor); ColorAttr lastAttr = null; for (Iterator<Object> i = parts.iterator(); cbuff.getVisibleLength() < len && i.hasNext();) { Object next = i.next(); if (next instanceof ColorAttr) { lastAttr = (Colo...
python
def exist_partitions(self, prefix_spec=None): """ Check if partitions with provided conditions exist. :param prefix_spec: prefix of partition :return: whether partitions exist """ try: next(self.partitions.iterate_partitions(spec=prefix_spec)) except ...
java
public EdgeLabel ensureEdgeLabelExist(final String edgeLabelName, final VertexLabel inVertexLabel, Map<String, PropertyType> properties) { return this.getSchema().ensureEdgeLabelExist(edgeLabelName, this, inVertexLabel, properties); }
java
@Override public void sawOpcode(int seen) { String message = null; try { stack.precomputation(this); if ((seen == Const.TABLESWITCH) || (seen == Const.LOOKUPSWITCH)) { int pc = getPC(); for (int offset : getSwitchOffsets()) { ...
java
protected SentryClient configureSentryClient(SentryClient sentryClient, Dsn dsn) { String release = getRelease(dsn); if (release != null) { sentryClient.setRelease(release); } String dist = getDist(dsn); if (dist != null) { sentryClient.setDist(dist); ...
java
public boolean intersect(Envelope3D other) { if (isEmpty() || other.isEmpty()) return false; if (other.xmin > xmin) xmin = other.xmin; if (other.xmax < xmax) xmax = other.xmax; if (other.ymin > ymin) ymin = other.ymin; if (other.ymax < ymax) ymax = other.ymax; if (other.zmin > zmin) z...
java
public Node<T> get(long value) { if (root == null) return null; if (value == first.value) return first; if (value == last.value) return last; if (value < first.value) return null; if (value > last.value) return null; return get(root, value); }
java
public void removeWorst(List<S> solutionSet) { // Find the worst; double worst = (double) solutionFitness.getAttribute(solutionSet.get(0)); int worstIndex = 0; double kappa = 0.05; for (int i = 1; i < solutionSet.size(); i++) { if ((double) solutionFitness.getAttribute(solutionSet.get(i)) > ...
java
protected MESubscription getSubscription(SIBUuid12 topicSpace, String topic) { return (MESubscription)iProxies.get(BusGroup.subscriptionKey(topicSpace, topic)); }
java
@Override public T get() throws FacebookException { if (base.get().isEmpty()) return null; else return base.get().get(0); }
python
def save_config(source=None, path=None): ''' .. versionadded:: 2019.2.0 Save the configuration to a file on the local file system. source: ``running`` The configuration source. Choose from: ``running``, ``candidate``, ``startup``. Default: ``running``. path ...
java
public static SaneSession withRemoteSane( InetAddress saneAddress, int port, long timeout, TimeUnit timeUnit, long soTimeout, TimeUnit soTimeUnit) throws IOException { long millis = timeUnit.toMillis(timeout); Preconditions.checkArgument( millis >= 0 && millis <...
java
@JsMethod(name = "getClassJsDoc", namespace = "jscomp") public static String getClassJsDoc(String jsDoc) { if (Strings.isNullOrEmpty(jsDoc)) { return null; } Config config = Config.builder() .setLanguageMode(LanguageMode.ECMASCRIPT3) .setStrictMode(Config.StrictMode.S...
java
public static double[][] appendColumns(final double[][] m1, final double[][] m2) { final int columndimension = getColumnDimensionality(m1); final int ccolumndimension = getColumnDimensionality(m2); assert m1.length == m2.length : "m.getRowDimension() != column.getRowDimension()"; final int rcolumndimen...
python
def v_grammar_unique_defs(ctx, stmt): """Verify that all typedefs and groupings are unique Called for every statement. Stores all typedefs in stmt.i_typedef, groupings in stmt.i_grouping """ defs = [('typedef', 'TYPE_ALREADY_DEFINED', stmt.i_typedefs), ('grouping', 'GROUPING_ALREADY_DEFI...
java
public boolean deleteUser(final long userId) throws SQLException { Connection conn = null; PreparedStatement stmt = null; try { conn = connectionSupplier.getConnection(); stmt = conn.prepareStatement(deleteUserSQL); stmt.setLong(1, userId); return stmt.executeUpdat...
python
def get_attribute_name_id(attr): """ Return the attribute name identifier """ return attr.value.id if isinstance(attr.value, ast.Name) else None
python
def pop(self, key, *args, **kwargs): """Remove and return the value associated with case-insensitive ``key``.""" return super(CaseInsensitiveDict, self).pop(CaseInsensitiveStr(key))
python
def _mix_latent_gp(W, g_mu, g_var, full_cov, full_output_cov): r""" Takes the mean and variance of an uncorrelated L-dimensional latent GP and returns the mean and the variance of the mixed GP, `f = W g`, where both f and g are GPs, with W having a shape [P, L] :param W: [P, L] :param g_mu: [.....
python
def _resolve_import(name): """Helper function for resolve_import.""" if name in sys.modules: return getattr(sys.modules[name], '__file__', name + '.so') return _resolve_import_versioned(name)
java
public void update(Object target) { if (target == null) { throw new IllegalArgumentException( "Target to update cannot be null"); } BeanWrapper bw = new BeanWrapperImpl(target); bw.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat...
java
static Bitmap decodeStream(InputStream stream, int requestedWidth, int requestedHeight, final boolean canShrink, Bitmap possibleAlternative, boolean closeStream) { BitmapFactory.Options options = standardBitmapFactoryOptions(); try { DecodeHelper helper; ...
python
def pack_new_sequence(self, sequence): """Packs a new sequence onto the polymer using Scwrl4. Parameters ---------- sequence : str String containing the amino acid sequence. This must be the same length as the Polymer Raises ------ ValueE...
java
public void addVertex(Vertex vertex) { if (!name.equals(vertex.baseName())) return; vertexes.add(vertex); }
java
protected <T> T getResponse(final WebTarget target, final ResponseProcessor<T> responseProcessor, final Request request) { Builder requestBuilder = target.request(); Response response = requestBuilder.buildGet().invoke(); if (response.getStatus() == Response.Status.OK.getStatusCode()) { InputStream in...
java
private void backwardCreateMessage(int edge) { if (!bg.isT1T2(edge) && (bg.t2E(edge) instanceof GlobalFactor)) { log.warn("ONLY FOR TESTING: Creating a single message from a global factor: " + edge); } if (bg.isT1T2(edge)) { backwardVarToFactor(edge); } else {...
java
public PactDslRequestWithPath bodyWithSingleQuotes(String body) { if (body != null) { body = QuoteUtil.convert(body); } return body(body); }
python
def add_action(self, node: Node) -> None: """ For each node, we accumulate the rules that generated its children in a list. """ if node.expr.name and node.expr.name not in ['ws', 'wsp']: nonterminal = f'{node.expr.name} -> ' if isinstance(node.expr, Literal): ...
java
public void stratify(int numFolds) { if (classAttribute().isNominal()) { // sort by class int index = 1; while (index < numInstances()) { Instance instance1 = instance(index - 1); for (int j = index; j < numInstances(); j++) { ...
java
public static Class<?>[] readClasses(ObjectInput in) throws java.io.IOException, ClassNotFoundException { int i, len; Class<?>[] result; len = in.readByte(); result = new Class[len]; for (i = 0; i < len; i++) { result[i] = read(in); } retu...
java
public Request post(String pathOrUri) { return new Request(this, Request.Method.POST, buildPath(pathOrUri)); }
java
@Override public void buildEnvironment(Run<?,?> build, EnvVars env) { Run run = getRun(); String value = (null == run) ? "UNKNOWN" : Jenkins.getInstance().getRootUrl() + run.getUrl(); env.put(name, value); env.put(name + ".jobName", getJobName()); // undocumented, left fo...
java
private Optional<PlanNode> coalesceWithNullAggregation(AggregationNode aggregationNode, PlanNode outerJoin, SymbolAllocator symbolAllocator, PlanNodeIdAllocator idAllocator, Lookup lookup) { // Create an aggregation node over a row of nulls. Optional<MappedAggregationInfo> aggregationOverNullInfoRes...
java
protected void trace(Throwable t, String msgFormat, Object... args) { m_logger.trace(String.format(msgFormat, args), t); }
python
def center_line(space, line): """ Add leading & trailing space to text to center it within an allowed width Parameters ---------- space : int The maximum character width allowed for the text. If the length of text is more than this value, no space will be added.\ line : str ...
java
public ObjectInstanceWrapper[] readObjectInstances(InputStream in) throws ConversionException, IOException { JSONArray json = parseArray(in); ObjectInstanceWrapper[] ret = new ObjectInstanceWrapper[json.size()]; int pos = 0; for (Object item : json) { ret[pos++] = readObjectI...
python
def set_sound_mode(self, sound_mode): """ Set sound_mode of device. Valid values depend on the device and should be taken from "sound_mode_list". Return "True" on success and "False" on fail. """ if sound_mode == ALL_ZONE_STEREO: if self._set_all_zone...
python
def get_snapshots(self, context): """ Returns list of snapshots :param context: resource context of the vCenterShell :type context: models.QualiDriverModels.ResourceCommandContext :return: """ resource_details = self._parse_remote_model(context) res = self...
java
private void exposeExposedFieldsToJs() { if (fieldsWithNameExposed.isEmpty()) { return; } MethodSpec.Builder exposeFieldMethod = MethodSpec .methodBuilder("vg$ef") .addAnnotation(JsMethod.class); fieldsWithNameExposed .forEach(field -> exposeFieldMethod .addSt...
java
private GeneralSubtree createWidestSubtree(GeneralNameInterface name) { try { GeneralName newName; switch (name.getType()) { case GeneralNameInterface.NAME_ANY: // Create new OtherName with same OID as baseName, but // empty value ...
java
public void setCycleInterval(float newCycleInterval) { if ( (this.cycleInterval != newCycleInterval) && (newCycleInterval > 0) ) { for (GVRNodeAnimation gvrKeyFrameAnimation : gvrKeyFrameAnimations) { //TODO Cannot easily change the GVRAnimation's GVRChannel once set. } ...
java
public static Matcher<Date> hasYearMonthAndDay(final int year, final int month, final int day) { return new IsDate(year, month, day); }
python
def _get_dataset(self, dataset, name, color): """ Encode a dataset """ global palette html = "{" html += '\t"label": "' + name + '",' if color is not None: html += '"backgroundColor": "' + color + '",\n' else: html += '"backgroundCo...
java
static Vector2d sum(final Tuple2d a, final Tuple2d b) { return new Vector2d(a.x + b.x, a.y + b.y); }
java
protected Object setInList(CachingPojoPath currentPath, PojoPathContext context, PojoPathState state, Object parentPojo, Object value, int index) { Object arrayOrList = convertList(currentPath, context, state, parentPojo); GenericBean<Object> arrayReceiver = new GenericBean<>(); Object convertedValue = val...
java
public static final Property propertyFor(RelationshipType rtype) { if (rtype == null) { throw new InvalidArgument("rtype", rtype); } return TYPETOPROPERTY.get(rtype); }
python
def is_move_legal(self, move): 'Checks that a move is on an empty space, not on ko, and not suicide' if move is None: return True if self.board[move] != EMPTY: return False if move == self.ko: return False if self.is_move_suicidal(move): ...
python
def request_change_variable(self, py_db, seq, thread_id, frame_id, scope, attr, value): ''' :param scope: 'FRAME' or 'GLOBAL' ''' py_db.post_method_as_internal_command( thread_id, internal_change_variable, seq, thread_id, frame_id, scope, attr, value)
java
public static boolean isProperPrefixPath(String firstPath, String secondPath) { firstPath = CmsStringUtil.joinPaths(firstPath, "/"); secondPath = CmsStringUtil.joinPaths(secondPath, "/"); return secondPath.startsWith(firstPath) && !firstPath.equals(secondPath); }
python
def urlopen(self, method, url, redirect=True, **kw): "Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute." u = parse_url(url) if u.scheme == "http": # For proxied HTTPS requests, httplib sets the necessary headers # on the CONNECT to the proxy. For HTTP, we'...
java
public static CommerceCountry[] findByG_A_PrevAndNext( long commerceCountryId, long groupId, boolean active, OrderByComparator<CommerceCountry> orderByComparator) throws com.liferay.commerce.exception.NoSuchCountryException { return getPersistence() .findByG_A_PrevAndNext(commerceCountryId, groupId, acti...
java
private AstNode nameOrLabel() throws IOException { if (currentToken != Token.NAME) throw codeBug(); int pos = ts.tokenBeg; // set check for label and call down to primaryExpr currentFlaggedToken |= TI_CHECK_LABEL; AstNode expr = expr(); if (expr.getType() !=...
java
public final WorkflowTemplate getWorkflowTemplate(WorkflowTemplateName name) { GetWorkflowTemplateRequest request = GetWorkflowTemplateRequest.newBuilder() .setName(name == null ? null : name.toString()) .build(); return getWorkflowTemplate(request); }
java
public List<Label> getStoryLabels() { if (!isAnnotationPresent(Stories.class)) { return Collections.emptyList(); } List<Label> result = new ArrayList<>(); for (String story : getAnnotation(Stories.class).value()) { result.add(createStoryLabel(story)); } ...
java
public Vector multiply(Vector vec) { x *= vec.x; y *= vec.y; z *= vec.z; return this; }
java
@SuppressWarnings("unchecked") @Override public EList<Double> getWeightsData() { return (EList<Double>) eGet(Ifc4Package.Literals.IFC_RATIONAL_BSPLINE_CURVE_WITH_KNOTS__WEIGHTS_DATA, true); }
python
def _set_type(self, v, load=False): """ Setter method for type, mapped from YANG variable /overlay/access_list/type (container) If this variable is read-only (config: false) in the source YANG file, then _set_type is considered as a private method. Backends looking to populate this variable should ...
java
public static void addFilePatternsToPackageResourceGuard(final Application application, final String... patterns) { final IPackageResourceGuard packageResourceGuard = application.getResourceSettings() .getPackageResourceGuard(); if (packageResourceGuard instanceof SecurePackageResourceGuard) { final Secu...
java
public static <E> Distribution<E> laplaceWithExplicitUnknown(Counter<E> counter, double lambda, E UNK) { Distribution<E> norm = new Distribution<E>(); norm.counter = new ClassicCounter<E>(); double total = counter.totalCount() + (lambda * (counter.size() - 1)); norm.numberOfKeys = counter.size(); ...
java
public void removeTableModelListener(TableModelListener l) { try { this.updateIfNewRow(-1); // Update any locked record. } catch (DBException ex) { ex.printStackTrace(); } super.removeTableModelListener(l); }
python
def remove(self, parent): """Remove an aggregation rule. Parameters ---------- parent : :class:`katcp.Sensor` object The aggregate sensor to remove. """ if parent not in self._aggregates: raise ValueError("Sensor %r does not have an aggregate rul...
java
private void processCalendarHours(ProjectCalendar calendar, Record dayRecord) { // ... for each day of the week Day day = Day.getInstance(Integer.parseInt(dayRecord.getField())); // Get hours List<Record> recHours = dayRecord.getChildren(); if (recHours.size() == 0) { // ...
java
public static PredictionEndpoint authenticate(String baseUrl, final String apiKey) { ServiceClientCredentials serviceClientCredentials = new ServiceClientCredentials() { @Override public void applyCredentialsFilter(OkHttpClient.Builder builder) { } }; return a...
python
def text(self): """ Gets the text of the Alert. """ if self.driver.w3c: return self.driver.execute(Command.W3C_GET_ALERT_TEXT)["value"] else: return self.driver.execute(Command.GET_ALERT_TEXT)["value"]
java
@Override public CharSegment getHeaderBuffer(String key) { int i = matchNextHeader(0, key); if (i >= 0) { return _headerValues[i]; } else { return null; } }
python
def read_namespaced_deployment_status(self, name, namespace, **kwargs): """ read status of the specified Deployment This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_deploymen...
python
def fresh_jwt_required(fn): """ A decorator to protect a Flask endpoint. If you decorate an endpoint with this, it will ensure that the requester has a valid and fresh access token before allowing the endpoint to be called. See also: :func:`~flask_jwt_extended.jwt_required` """ @wraps(...
java
public static void downloadOSMFile(File file, Envelope geometryEnvelope) throws IOException { HttpURLConnection urlCon = (HttpURLConnection) createOsmUrl(geometryEnvelope).openConnection(); urlCon.setRequestMethod("GET"); urlCon.connect(); switch (urlCon.getResponseCode()) { ...
java
public ServiceFuture<AvailableProvidersListInner> beginListAvailableProvidersAsync(String resourceGroupName, String networkWatcherName, AvailableProvidersListParameters parameters, final ServiceCallback<AvailableProvidersListInner> serviceCallback) { return ServiceFuture.fromResponse(beginListAvailableProviders...
python
def rpm_qf_args(tags=None, separator=';'): """ Return the arguments to pass to rpm to list RPMs in the format expected by parse_rpm_output. """ if tags is None: tags = image_component_rpm_tags fmt = separator.join(["%%{%s}" % tag for tag in tags]) return r"-qa --qf '{0}\n'".format(...
java
@Override public void setValueAt(final Object value, final List<Integer> row, final int col) { if (!isEditable()) { throw new IllegalStateException("Attempted to set a value on an uneditable model"); } Object rowBean = getRowBean(row); if (rowBean == null) { return; } int lvlIndex = getLevelIndex(r...
python
def _initializeLocationCache(self): """ CGD uses Faldo ontology for locations, it's a bit complicated. This function sets up an in memory cache of all locations, which can be queried via: locationMap[build][chromosome][begin][end] = location["_id"] """ # cache of ...
python
def _update_listing_client_kwargs(client_kwargs, max_request_entries): """ Updates client kwargs for listing functions. Args: client_kwargs (dict): Client arguments. max_request_entries (int): If specified, maximum entries returned by request. Re...
java
protected void doSetFrom(String from, String personal) { assertArgumentNotEmpty("from", from); assertArgumentNotEmpty("personal", personal); // only from required postcard.setFrom(createAddress(from, personal)); }
java
@Deprecated public ServerBuilder sslContext( SessionProtocol protocol, File keyCertChainFile, File keyFile) throws SSLException { defaultVirtualHostBuilderUpdated(); defaultVirtualHostBuilder.sslContext(protocol, keyCertChainFile, keyFile); return this; }
python
def find_or_create_all(cls, list_of_kwargs, keys=[]): """Batch method for querying for a list of instances and creating them if required Args: list_of_kwargs(list of dicts): A list of dicts where each dict denotes the keyword args that you would pass ...
java
public static Calendar popCalendar(long timeInMillis) { Calendar calendar = popCalendar(); calendar.setTimeInMillis(timeInMillis); return calendar; }
java
public void setDefaultDeliverySettings(com.google.api.ads.admanager.axis.v201805.MediaLocationSettings defaultDeliverySettings) { this.defaultDeliverySettings = defaultDeliverySettings; }
java
private FragmentInstance createNewInstance() { try { return (FragmentInstance) getBackingClass().newInstance(); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } }
java
private long getChunkSize() throws IOException { final int st = this.state; switch (st) { case CHUNK_CRLF: this.buffer.clear(); final int bytesRead1 = this.in.readLine(this.buffer); if (bytesRead1 == -1) { throw new MalformedChunkCodingExceptio...
python
def _init_action_list(self, action_filename): """Parses the file and populates the data.""" self.actions = list() self.hiid_to_action_index = dict() f = codecs.open(action_filename, 'r', encoding='latin-1') first_line = True for line in f: line = line.rstrip...
java
private HtmlResponse asListHtml() { return asHtml(path_AdminSearchlog_AdminSearchlogJsp).renderWith(data -> { RenderDataUtil.register(data, "searchLogItems", searchLogService.getSearchLogList(searchLogPager)); // page navi }).useForm(SearchForm.class, setup -> { setup.setup(f...
python
def run_coroutine_threadsafe(self, coro, loop=None, callback=None): """Be used when loop running in a single non-main thread.""" if not asyncio.iscoroutine(coro): raise TypeError("A await in coroutines. object is required") loop = loop or self.loop future = NewFuture(callback...