language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def connection_open(self) -> None: """ Callback when the WebSocket opening handshake completes. Enter the OPEN state and start the data transfer phase. """ # 4.1. The WebSocket Connection is Established. assert self.state is State.CONNECTING self.state = State.O...
python
def open(self, directory=None, filename=None, mode="rb"): """Opens a file for writing or reading.""" path = os.path.join(directory, filename) return open(path, mode)
java
public ServiceFuture<List<ProjectInner>> listAsync(final String groupName, final String serviceName, final ListOperationCallback<ProjectInner> serviceCallback) { return AzureServiceFuture.fromPageResponse( listSinglePageAsync(groupName, serviceName), new Func1<String, Observable<ServiceR...
python
def create_mixin(self): """ This will create the custom Model Mixin to attach to your custom field enabled model. :return: """ _builder = self class CustomModelMixin(object): @cached_property def _content_type(self): retu...
java
@Override public CreateDatasetResult createDataset(CreateDatasetRequest request) { request = beforeClientExecution(request); return executeCreateDataset(request); }
python
def transfer_funds(self, to, amount, denom, msg): ''' Transfer SBD or STEEM to the given account ''' try: self.steem_instance().commit.transfer(to, float(amount), denom, msg, self.mainaccount) except Exception as e: self.msg.error_message(e) ...
python
def group_associations(self, params=None): """ Gets the group association from a Indicator/Group/Victim Yields: Group Association """ if params is None: params = {} if not self.can_update(): self._tcex.handle_error(910, [self.type]) ...
java
@Override public BandMatrix transpose() { BandMatrix at = new BandMatrix(n, m2, m1); for (int i = 0; i < n; i++) { for (int j = i-m2; j <= i+m1; j++) { if (j >= 0 && j < n) { at.set(i, j, get(j, i)); } } } r...
java
@Override public EClass getIfcElectricCurrentMeasure() { if (ifcElectricCurrentMeasureEClass == null) { ifcElectricCurrentMeasureEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(802); } return ifcElectricCurrentMeasureEClass; }
python
def chat_post_message(self, channel, text, **params): """chat.postMessage This method posts a message to a channel. https://api.slack.com/methods/chat.postMessage """ method = 'chat.postMessage' params.update({ 'channel': channel, 'text': text, ...
java
public JobFolder createJobFolderWithApplicationId(final String applicationId) throws IOException { final Path jobFolderPath = jobSubmissionDirectoryProvider.getJobSubmissionDirectoryPath(applicationId); final String finalJobFolderPath = jobFolderPath.toString(); LOG.log(Level.FINE, "Final job submission Dir...
python
def mine_block(chain: MiningChain, **kwargs: Any) -> MiningChain: """ Mine a new block on the chain. Header parameters for the new block can be overridden using keyword arguments. """ if not isinstance(chain, MiningChain): raise ValidationError('`mine_block` may only be used on MiningChain...
python
def iiscgi(application): """A specialized version of the reference WSGI-CGI server to adapt to Microsoft IIS quirks. This is not a production quality interface and will behave badly under load. """ try: from wsgiref.handlers import IISCGIHandler except ImportError: print("Python 3.2 or newer is required.") ...
java
protected boolean isDeleteAllowed(String key) { // check internal handlers first for (ISharedObjectSecurity handler : securityHandlers) { if (!handler.isDeleteAllowed(this, key)) { return false; } } // check global SO handlers next ...
python
def rate_entry_courses(self, topic_id, entry_id, course_id, rating=None): """ Rate entry. Rate a discussion entry. On success, the response will be 204 No Content with an empty body. """ path = {} data = {} params = {} # REQU...
java
public static void intIndexesToBooleanArray(int[] arra, boolean[] arrb) { for (int i = 0; i < arra.length; i++) { if (arra[i] < arrb.length) { arrb[arra[i]] = true; } } }
python
def selectable_delete(self) -> Expectation: ''' Remove two projects by selecting them via `<space>` and pressing `d` ''' self.cmd_sync('ProAdd! tpe2/dep') self._count(2) self.cmd_sync('Projects') self.cmd_sync('call feedkeys("\\<space>\\<space>d")') return...
python
def extract_spectra_from_file( log, pathToSpectrum, convertLumToFlux=False): """ *Given a spectrum file this function shall convert the two columns (wavelength and luminosity) to a wavelegnth (wavelengthArray) and flux (fluxArray) array* **Key Arguments:** - ``log`` -- logge...
java
public void sendfile(OutputStream os, long offset, long length) throws IOException { if (os instanceof OutputStreamWithBuffer) { writeToStream((OutputStreamWithBuffer) os); } else { writeToStream(os); } }
python
def _callback(self): """The actual callback.""" if self.debug: # Show the number of open file descriptors print(">>>>> _callback: Number of open file descriptors: %s" % get_open_fds()) self._runem_all() # Mission accomplished. Shutdown the scheduler. all...
java
protected <T> void writeArray(T[] values, WriteOp<T> writer) { writeList(Arrays.asList(values), writer); }
python
def parse_options_header(value): """Parse a ``Content-Type`` like header into a tuple with the content type and the options: >>> parse_options_header('text/html; charset=utf8') ('text/html', {'charset': 'utf8'}) This should not be used to parse ``Cache-Control`` like headers that use a slightl...
java
@Override public Set<IPersonAttributes> getPeopleWithMultivaluedAttributes(final Map<String, List<Object>> seed, final IPersonAttributeDaoFilter filter) { Validate.notNull(seed, "Argument 'seed' cannot be null."); if (patterns == ...
python
def quarter_to_daterange(quarter): """Convert a quarter in arbitrary filename-ready format (e.g. 2015Q1) into start and end datetimes""" assert len(quarter) == 6 year = int(quarter[0:4]) quarter = quarter[5] MONTH_DAY = { '1': ((1, 1), (3, 31)), '2': ((4, 1), (6, 30)), '3...
python
def read_xml(filename): """ Use et to read in a xml file, or string, into a Element object. :param filename: File to parse. :return: lxml._elementTree object or None """ parser = et.XMLParser(remove_blank_text=True) isfile=False try: isfile = os.path.exists(filename) except ...
java
public String[] getServices(Database database, String servicename, String instname) throws DevFailed { Vector<String> v = new Vector<String>(); char separ; // Read Service property DbDatum datum = get_property(database, TangoConst.CONTROL_SYSTEM, TangoConst.S...
java
public <T extends Object> T load(Class<T> clazz, Object hashKey, DynamoDBMapperConfig config) { return load(clazz, hashKey, null, config); }
python
def p2sh(self, s): """ Parse a pay-to-script-hash address. Return a :class:`Contract` or None. """ data = self.parse_b58_hashed(s) if (None in (data, self._pay_to_script_prefix) or not data.startswith(self._pay_to_script_prefix)): return None ...
python
def _protobuf_value_type(value): """Returns the type of the google.protobuf.Value message as an api.DataType. Returns None if the type of 'value' is not one of the types supported in api_pb2.DataType. Args: value: google.protobuf.Value message. """ if value.HasField("number_value"): return api_pb2...
python
def pOparapar(self,Opar,apar,tdisrupt=None): """ NAME: pOparapar PURPOSE: return the probability of a given parallel (frequency,angle) offset pair INPUT: Opar - parallel frequency offset (array) (can be Quantity) apar - parallel angle off...
python
def getroot(self): """Return the root element of the figure. The root element is a group of elements after stripping the toplevel ``<svg>`` tag. Returns ------- GroupElement All elements of the figure without the ``<svg>`` tag. """ if 'class'...
java
private void addToolbarButtons() { Button add = CmsToolBar.createButton( FontOpenCms.WAND, CmsVaadinUtils.getMessageText(Messages.GUI_RESOURCETYPE_CREATE_NEW_TYPE_0)); add.addClickListener(new ClickListener() { private static final long serialVersionUID = 1L; ...
python
async def parse_response(self, block=True, timeout=0): "Parse the response from a publish/subscribe command" connection = self.connection if connection is None: raise RuntimeError( 'pubsub connection not set: ' 'did you forget to call subscribe() or ps...
java
public static String getSelectColumns(Class<?> entityClass) { EntityTable entityTable = getEntityTable(entityClass); if (entityTable.getBaseSelect() != null) { return entityTable.getBaseSelect(); } Set<EntityColumn> columnList = getColumns(entityClass); StringBuilder ...
python
def get_object(self, ObjectClass, id): """ Retrieve object of type ``ObjectClass`` by ``id``. | Returns object on success. | Returns None otherwise. """ try: object = ObjectClass.objects.get(id=id) except (ObjectClass.DoesNotExist, ObjectClass.MultipleObjects...
java
public void marshall(Namespace namespace, ProtocolMarshaller protocolMarshaller) { if (namespace == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(namespace.getId(), ID_BINDING); protocol...
python
def join(self, table, one=None, operator=None, two=None, type='inner', where=False): """ Add a join clause to the query :param table: The table to join with, can also be a JoinClause instance :type table: str or JoinClause :param one: The first column of the join c...
python
def finish(self, job_id, queue_id, queue_type='default'): """Marks any dequeued job as *completed successfully*. Any job which gets a finish will be treated as complete and will be removed from the SharQ. """ if not is_valid_identifier(job_id): raise BadArgumentExcept...
java
PathMatcher.PathMatch<HostEntry> match(String path){ int length = path.length(); final int[] lengths = this.lengths; for (int i = 0; i < lengths.length; ++i) { int pathLength = lengths[i]; if (pathLength == length) { HostEntry next = contexts.get(path); ...
java
public java.lang.String getXmlns() { return (java.lang.String) getStateHelper().eval(PropertyKeys.xmlns); }
python
def update_pipe_module(): """Populate the pipe module dynamically.""" module_dir = __all__ operators = stream.__dict__ for key, value in operators.items(): if getattr(value, 'pipe', None): globals()[key] = value.pipe if key not in module_dir: module_dir.ap...
python
def pretty_print(self, carrot=False): """Return a string of this line including linenumber. If carrot is True then a line is added under the string with a carrot under the current character position. """ lineno = self.lineno padding = 0 if lineno < 1000: ...
java
public ReceiveMessageResult receiveMessage(String queueUrl) { ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(queueUrl); return receiveMessage(receiveMessageRequest); }
java
public String format(String s) { for(int i = 0; i < s.length(); i++) { if(s.substring(i, i + 1).equals("*") && i > 0) if(isOperand(s.substring(i - 1, i), var) && i < s.length() - 1 && s.substring(i + 1, i + 2).equals(var)) s = s.substring(0, i) + s.substring(i...
java
public void close() { super.clear(); if (indexMap != null){ indexMap.clear(); indexMap = null; } if (this.indexStore != null){ getIndexStore().close(); this.indexStore = null ; } if (this.cacheStore != null){ getCacheStore().close(); this.cacheStore = null ; } }
python
def _updateEndpoints(self,*args,**kwargs): """ Updates all endpoints except the one from which this slot was called. Note: this method is probably not complete threadsafe. Maybe a lock is needed when setter self.ignoreEvents """ sender = self.sender() if not self.ignore...
python
def render(self, name, value, attrs=None): '''Render the widget as HTML inputs for display on a form. :param name: form field base name :param value: date value :param attrs: - unused :returns: HTML text with three inputs for year/month/day ''' # expects a value...
python
def split_levels(fields): """ Convert dot-notation such as ['a', 'a.b', 'a.d', 'c'] into current-level fields ['a', 'c'] and next-level fields {'a': ['b', 'd']}. """ first_level_fields = [] next_level_fields = {} if not fields: return first_level_fields, next_level_f...
python
def csch(x, context=None): """ Return the hyperbolic cosecant of x. """ return _apply_function_in_current_context( BigFloat, mpfr.mpfr_csch, (BigFloat._implicit_convert(x),), context, )
java
public void addString(String str) { if (sourceNode != null) { addStringInternal(str); replaceOrRegister(sourceNode, str); } else { unSimplify(); addString(str); } }
python
def clear(self): """Empty the instance """ # self.graph = nx.Graph() self.graph.clear() self.data.clear() self.descriptors.clear() self.size2d = None self.rings = None self.scaffolds = None self.isolated = None
java
public Observable<ServiceResponse<Page<DeletedStorageAccountItem>>> getDeletedStorageAccountsWithServiceResponseAsync(final String vaultBaseUrl) { return getDeletedStorageAccountsSinglePageAsync(vaultBaseUrl) .concatMap(new Func1<ServiceResponse<Page<DeletedStorageAccountItem>>, Observable<ServiceRe...
python
def _set_prompt(self): """Set prompt so it displays the current working directory.""" self.cwd = os.getcwd() self.prompt = Fore.CYAN + '{!r} $ '.format(self.cwd) + Fore.RESET
python
def transfer_all(cls, field_mappings, sources, destination_factory=None): """Calls cls.transfer on all records in sources.""" for index, source in enumerate(sources): try: yield cls.transfer(field_mappings, source, destination_factory or (lambda x: x)) except Exception as ex: raise E...
python
def by_re_lookup(self, style_key, style_value, re_flags=0): """Return a processor for a "re_lookup" style value. Parameters ---------- style_key : str A style key. style_value : dict A dictionary with a "re_lookup" style value that consists of a ...
java
public java.util.List<InstanceInformation> getInstanceInformationList() { if (instanceInformationList == null) { instanceInformationList = new com.amazonaws.internal.SdkInternalList<InstanceInformation>(); } return instanceInformationList; }
python
def getSiblings(self, textId, subreference): """ Retrieve the siblings of a textual node :param textId: PrototypeText Identifier :type textId: str :param subreference: Passage Reference :type subreference: str :return: Tuple of references :rtype: (str, str) ...
python
async def search_raw(self, term: str, limit: int = 3) -> List[dict]: """Performs a search for a term and returns the raw response. Args: term: The term to be defined. limit: The maximum amount of results you'd like. Defaults to 3. ...
python
def handle_error(self, error, req, schema, error_status_code, error_headers): """Handles errors during parsing. Aborts the current HTTP request and responds with a 422 error. """ status_code = error_status_code or self.DEFAULT_VALIDATION_STATUS abort( status_code, ...
python
def cli(*args, **kwargs): """ CSVtoTable commandline utility. """ # Convert CSV file content = convert.convert(kwargs["input_file"], **kwargs) # Serve the temporary file in browser. if kwargs["serve"]: convert.serve(content) # Write to output file elif kwargs["output_file"]:...
python
def missing_count(self): """numeric representing count of missing rows in cube response.""" if self.means: return self.means.missing_count return self._cube_dict["result"].get("missing", 0)
python
def config_list(backend): """ Print the current configuration """ click.secho('Print Configuration', fg='green') print str(backend.dki.get_config())
python
def _filter_deleted_records(self, batches): """ Filter out deleted records """ for batch in batches: for record in batch: if not self.must_delete_record(record): yield record
python
def add_pii_permissions(self, group, view_only=None): """Adds PII model permissions. """ pii_model_names = [m.split(".")[1] for m in self.pii_models] if view_only: permissions = Permission.objects.filter( (Q(codename__startswith="view") | Q(codename__startswit...
java
public CMAUiExtension update(CMAUiExtension extension) { assertNotNull(extension, "extension"); final Integer version = getVersionOrThrow(extension, "update"); final String id = getResourceIdOrThrow(extension, "extension"); final String spaceId = getSpaceIdOrThrow(extension, "extension"); assertNotN...
java
@Override public com.liferay.commerce.product.model.CProduct addCProduct( com.liferay.commerce.product.model.CProduct cProduct) { return _cProductLocalService.addCProduct(cProduct); }
python
def padtype_to_pads(in_shape, window_shape, window_strides, padding): """Convert padding string to list of pairs of pad values.""" padding = padding.upper() if padding == 'SAME': out_shape = onp.ceil( onp.true_divide(in_shape, window_strides)).astype(int) pad_sizes = [max((out_size - 1) * stride +...
java
@Override public StopContinuousExportResult stopContinuousExport(StopContinuousExportRequest request) { request = beforeClientExecution(request); return executeStopContinuousExport(request); }
java
@Override public void play(SpeechAnnouncement announcement) { boolean isInvalidAnnouncement = announcement == null; if (isInvalidAnnouncement) { return; } this.announcement = announcement; playAnnouncementTextAndTypeFrom(announcement); }
python
def connect_params_async(self): """Connection parameters for `aiomysql.Connection` """ kwargs = self.connect_params.copy() kwargs.update({ 'minsize': self.min_connections, 'maxsize': self.max_connections, 'autocommit': True, }) return k...
python
def id(self, opts_id): """Handles tracking and cleanup of custom ids.""" old_id = self._id self._id = opts_id if old_id is not None: cleanup_custom_options(old_id) if opts_id is not None and opts_id != old_id: if opts_id not in Store._weakrefs: ...
python
def geocode( self, query, bbox=None, mapview=None, exactly_one=True, maxresults=None, pageinformation=None, language=None, additional_data=False, timeout=DEFAULT_SENTINEL ): """ Re...
java
public void run() { MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); ObjectName os; try { os = new ObjectName("java.lang:type=OperatingSystem"); } catch( MalformedObjectNameException e ) { throw Log.throwErr(e); } Thread.currentThread().setPriority(Thread.MAX_PRIORITY); ...
java
public static boolean isNonStandard(GeometryType geometryType) { return GeometryCodes.getCode(geometryType) > GeometryCodes .getCode(GeometryType.SURFACE); }
java
protected void inject(final Object target, final Field field, Object value) throws IllegalAccessException { field.set(target, value); }
java
@Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case AfplibPackage.WINDOW_SPECIFICATION__FLAGS: return getFLAGS(); case AfplibPackage.WINDOW_SPECIFICATION__RES3: return getRES3(); case AfplibPackage.WINDOW_SPECIFICATION__CFORMAT: return getCF...
python
def api_request(self, url, data=None, method='GET', raw=False, file=None): """ Perform an API request to the given URL, optionally including the specified data :type url: String :param url: the URL to which to make the request :type data: String :param data: the data to ...
python
def predict(self, X): """Predict for X. For dask inputs, a dask array or dataframe is returned. For other inputs (NumPy array, pandas dataframe, scipy sparse matrix), the regular return value is returned. Parameters ---------- X : array-like Returns ...
python
def create_engine(engine, options=None, defaults=None): ''' Creates an instance of an engine. There is a two-stage instantiation process with engines. 1. ``options``: The keyword options to instantiate the engine class 2. ``defaults``: The default configuration for the engine (optio...
python
def _onerror(cls, kmsg, result): """ To execute on execution failure :param kser.schemas.Message kmsg: Kafka message :param kser.result.Result result: Execution result :return: Execution result :rtype: kser.result.Result """ logger.error( "{}.Failed: ...
python
def compile_theme(theme_id=None): """Compiles a theme.""" from engineer.processors import convert_less from engineer.themes import ThemeManager if theme_id is None: themes = ThemeManager.themes().values() else: themes = [ThemeManager.theme(theme_id)] with(indent(2)): pu...
python
def get_topic_count(self): """ get_topic_count: get number of topics in tree Args: None Returns: int """ total = 0 if self.kind == content_kinds.TOPIC or self.kind == "Channel": total = 1 for child in self.children: total +=...
python
def get_default_config(self): """ Returns the default collector settings """ config = super(HAProxyCollector, self).get_default_config() config.update({ 'method': 'http', 'path': 'haproxy', 'url': 'http://loca...
java
public Iterable<String> components() { ImmutableList.Builder<String> components = ImmutableList.builder(); buildComponents(components); return components.build(); }
java
public Record getRecordAt(int i) { i -= DBConstants.MAIN_FIELD; // Zero based index try { return (Record)this.elementAt(i); } catch (ArrayIndexOutOfBoundsException e) { } return null; // Not found }
java
public void unscheduleJob(String jobName) throws JobException { if (this.scheduledJobs.containsKey(jobName)) { try { this.scheduler.getScheduler().deleteJob(this.scheduledJobs.remove(jobName)); } catch (SchedulerException se) { LOG.error("Failed to unschedule and delete job " + job...
java
private boolean discoverGlobalFaultData_rcv(Set<Long> hsIds) { long blockedOnReceiveStart = System.currentTimeMillis(); long lastReportTime = 0; boolean haveEnough = false; int [] forwardStallCount = new int[] {FORWARD_STALL_COUNT}; do { VoltMessage m = m_mailbox.re...
java
public void setConfigurationAggregatorNames(java.util.Collection<String> configurationAggregatorNames) { if (configurationAggregatorNames == null) { this.configurationAggregatorNames = null; return; } this.configurationAggregatorNames = new com.amazonaws.internal.SdkInte...
python
def _estimate_centers_widths( self, unique_R, inds, X, W, init_centers, init_widths, template_centers, template_widths, template_centers_mean_cov, template_widths_mean_var_reci): "...
python
def debug_string(self, max_debug=MAX_DEBUG_TRIALS): """Returns a human readable message for printing to the console.""" messages = self._debug_messages() states = collections.defaultdict(set) limit_per_state = collections.Counter() for t in self._trials: states[t.stat...
java
public ServiceFuture<Void> beginTerminateAsync(String resourceGroupName, String workspaceName, String experimentName, String jobName, final ServiceCallback<Void> serviceCallback) { return ServiceFuture.fromResponse(beginTerminateWithServiceResponseAsync(resourceGroupName, workspaceName, experimentName, jobName)...
python
def search(request, spec, operator='and'): """ Search the package database using the indicated search spec. The spec may include any of the keywords described in the above list (except 'stable_version' and 'classifiers'), for example: {'description': 'spam'} will search description fields. With...
python
def decode_file_args(self, argv: List[str]) -> List[str]: """ Preprocess a configuration file. The location of the configuration file is stored in the parser so that the FileOrURI action can add relative locations. :param argv: raw options list :return: options list with '--conf...
java
HttpRedirectionValidator getRedirectionValidator() { if (redirectionValidator == null) { redirectionValidator = redirection -> { if (!nodeInScope(redirection.getEscapedURI())) { if (log.isDebugEnabled()) { log.debug("Skipping redirecti...
java
private ZealotKhala doLike(String prefix, String field, Object value, boolean match, boolean positive) { if (match) { String suffix = positive ? ZealotConst.LIKE_KEY : ZealotConst.NOT_LIKE_KEY; SqlInfoBuilder.newInstace(this.source.setPrefix(prefix).setSuffix(suffix)).buildLikeSql(field,...
python
def get_all_source(self, **kwargs): # noqa: E501 """Get all sources for a customer # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_all_source(async_req=Tr...
java
private Pair<Long, Integer> updateCooked(byte[] compressedData) { // Uncompress (inflate) the bytes. byte[] cookedBytes; try { cookedBytes = gunzipBytes(compressedData); } catch (IOException e) { throw new RuntimeException("Unable to decompress elastic hashinator ...
java
public Matrix4f invert(Matrix4f dest) { if ((properties & PROPERTY_IDENTITY) != 0) { return dest.identity(); } else if ((properties & PROPERTY_TRANSLATION) != 0) return invertTranslation(dest); else if ((properties & PROPERTY_ORTHONORMAL) != 0) return invertOr...
java
public static byte[] createType1Message(String workStation, String domain, Integer customFlags, byte[] osVersion) { byte[] msg; if (osVersion != null && osVersion.length != 8) { throw new IllegalArgumentException( "osVersion parameter should be a 8 byte wide ...
python
def _encode_filename(filename): # pragma: no cover """Return a byte string suitable for a filename. Unicode is encoded using an encoding adapted to what both cairo and the filesystem want. """ # Don't replace unknown characters as '?' is forbidden in Windows filenames errors = 'ignore' if os....