language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def start( self, phone=lambda: input('Please enter your phone (or bot token): '), password=lambda: getpass.getpass('Please enter your password: '), *, bot_token=None, force_sms=False, code_callback=None, first_name='New User', last_name='', max_att...
python
def choose(n, k): """ A fast way to calculate binomial coefficients by Andrew Dalke (contrib). """ if 0 <= k <= n: ntok = 1 ktok = 1 for t in xrange(1, min(k, n - k) + 1): ntok *= n ktok *= t n -= 1 return ntok // ktok else: ...
java
public static TreeElement getRoot(TreeElement node) { TreeElement parentNode = node.getParent(); while (parentNode != null) { node = parentNode; parentNode = node.getParent(); } return node; }
java
private UIForm getForm(UIComponent component) { while (component != null) { if (component instanceof UIForm) { break; } component = component.getParent(); } return (UIForm) component; }
java
public ApiSuccessResponse setAgentStateNotReady(NotReadyData notReadyData) throws ApiException { ApiResponse<ApiSuccessResponse> resp = setAgentStateNotReadyWithHttpInfo(notReadyData); return resp.getData(); }
java
private void handleNullMarshaller() { try { // First see if marshalling is in the class path - if so we can use the generic marshaller // We have to use the commons class loader, since marshalling is its dependency Class.forName("org.jboss.marshalling.river.RiverMarshaller", false, Util...
java
public static String slurp(final InputStream is, final int bufferSize) { final char[] buffer = new char[bufferSize]; final StringBuilder out = new StringBuilder(); try { final Reader in = new InputStreamReader(is, "UTF-8"); try { for (;;) { int rsz = in.read(buffer, 0, buffer.length); if (rsz ...
java
@Override public CreateDeploymentConfigResult createDeploymentConfig(CreateDeploymentConfigRequest request) { request = beforeClientExecution(request); return executeCreateDeploymentConfig(request); }
java
public ApiSuccessResponse hold(String id, HoldData holdData) throws ApiException { ApiResponse<ApiSuccessResponse> resp = holdWithHttpInfo(id, holdData); return resp.getData(); }
java
int getIdForResource(@NonNull Context context, @StyleableRes int index) { final int[] attrs = new int[]{index}; final TypedArray typedArray = context.getTheme().obtainStyledAttributes(styleRes, attrs); int id = typedArray.getResourceId(0, -1); typedArray.recycle(); return id; ...
python
def attach_schema(self, schem): """Add a tuple schema to this object (externally imposed)""" self.tuple_schema = schema.AndSchema.make(self.tuple_schema, schem)
python
def gradients_XX_diag(self, dL_dK_diag, X): """ Given the derivative of the objective dL_dK, compute the second derivative of K wrt X: ..math: \frac{\partial^2 K}{\partial X\partial X} ..returns: dL2_dXdX: [NxQxQ] """ dL_dK_diag = dL_dK_diag.copy()...
python
def raw(self): """A raw asynchronous Http response """ if self._raw is None: self._raw = HttpStream(self) return self._raw
python
def foreign_key(*args, fk_col: Optional[str] = None, primary_key: bool = False, nullable: bool = False, **kwargs, ) -> Column: """ Helper method to add a foreign key column to a model. For example:: class Post(db.Model...
python
async def _build_rr_delta_json(self, rr_id: str, to: int, fro: int = None, fro_delta: dict = None) -> (str, int): """ Build rev reg delta json, potentially starting from existing (earlier) delta. Return delta json and its timestamp on the distributed ledger. Raise AbsentRevReg for no s...
python
def stop(self): """Stop execution of all current and future payloads""" if not self.running.wait(0.2): return self._logger.debug('runner disabled: %s', self) with self._lock: self.running.clear() self._stopped.wait()
python
def sbytes2ilines(stream, encoding="utf8", closer=None): """ CONVERT A STREAM (with read() method) OF (ARBITRARY-SIZED) byte BLOCKS TO A LINE (CR-DELIMITED) GENERATOR """ def read(): try: while True: bytes_ = stream.read(4096) if not bytes_: ...
python
def _get_controller_agent(self, arg): """Return a single or a complex controller agent.""" controller_agent = None controller = arg.get('arg') # There is either a single controller here if controller is not None: controller_agent, coords = self._get_agent_from_entity(...
python
def getRenderModelName(self, unRenderModelIndex, pchRenderModelName, unRenderModelNameLen): """ Use this to get the names of available render models. Index does not correlate to a tracked device index, but is only used for iterating over all available render models. If the index is out of rang...
python
def plot_ltt(lineages, show_plot=True, color='#000000', xmin=None, xmax=None, ymin=None, ymax=None, title=None, xlabel=None, ylabel=None): '''Plot the Lineages Through Time (LTT) curve of a given tree Args: ``lineages`` (``dict``): The ``lineages`` dictionary returned by a ``Tree`` object's ``lineages_...
java
synchronized String registerHandle(AbstractAppHandle handle) { String secret = createSecret(); secretToPendingApps.put(secret, handle); return secret; }
java
public boolean execute() { try { coroutine.run(continuation); continuation.successExecutionCycle(); } catch (Exception e) { continuation.failedExecutionCycle(); throw new CoroutineException("Exception thrown during execution", e); } ...
python
def resolve_attr(obj, path): """A recursive version of getattr for navigating dotted paths. Args: obj: An object for which we want to retrieve a nested attribute. path: A dot separated string containing zero or more attribute names. Returns: The attribute referred to by obj.a1.a2.a...
python
def cipher(self): """Applies the Caesar shift cipher. Based on the attributes of the object, applies the Caesar shift cipher to the message attribute. Accepts positive and negative integers as offsets. Required attributes: message offset Returns...
python
def _parse_args(): """Parse and return command line arguments.""" parser = argparse.ArgumentParser( description=__doc__, formatter_class=_CliFormatter) parser.add_argument('-v', '--verbose', action='store_true', help='Enable verbose output.') fb_group = parser.ad...
python
def lastId(self): """ Children passage :rtype: str :returns: First children of the graph. Shortcut to self.graph.children[0] """ if self._last is False: # Request the next urn self._last = self.childIds[-1] return self._last
python
def update_search_letters(self, text): """Update search letters with text input in search box.""" self.letters = text names = [shortcut.name for shortcut in self.shortcuts] results = get_search_scores(text, names, template='<b>{0}</b>') self.normal_text, self.rich_text, self...
java
public ServiceFuture<ProjectFileInner> createOrUpdateAsync(String groupName, String serviceName, String projectName, String fileName, ProjectFileInner parameters, final ServiceCallback<ProjectFileInner> serviceCallback) { return ServiceFuture.fromResponse(createOrUpdateWithServiceResponseAsync(groupName, servic...
python
def _describe_type(arg): """Describe given argument, including length if it's a tuple. The purpose is to prevent nonsensical exception messages such as:: expected a tuple of length 2, got tuple expected a tuple, got tuple by turning them into:: expected a tuple of length 3, got t...
java
@Override public Request<ModifySpotFleetRequestRequest> getDryRunRequest() { Request<ModifySpotFleetRequestRequest> request = new ModifySpotFleetRequestRequestMarshaller().marshall(this); request.addParameter("DryRun", Boolean.toString(true)); return request; }
python
def get_param_info(self, obj, include_super=True): """ Get the parameter dictionary, the list of modifed parameters and the dictionary or parameter values. If include_super is True, parameters are also collected from the super classes. """ params = dict(obj.param.objects...
java
@Nullable public static String generateQueryString(Map<String, String> queryMap) { if (queryMap == null || queryMap.isEmpty()) { return null; } ArrayList<String> pairs = new ArrayList<>(queryMap.size()); try { for (Map.Entry<String, String> entry : queryMap.entrySet()) { pairs.add(...
java
private Content processParamTag(boolean isNonTypeParams, TagletWriter writer, ParamTag paramTag, String name, boolean isFirstParam) { Content result = writer.getOutputInstance(); String header = writer.configuration().getText( isNonTypeParams ? "doclet.Parameters" : "...
python
def parseLine(line, lineNumber=None): """ Parse line """ match = line_re.match(line) if match is None: raise ParseError("Failed to parse line: {0!s}".format(line), lineNumber) # Underscores are replaced with dash to work around Lotus Notes return (match.group('name').replace('_', '-'...
java
private boolean isAnnotationArray(AnnotationDesc.ElementValuePair[] pairs) { AnnotationValue annotationValue; for (AnnotationDesc.ElementValuePair pair : pairs) { annotationValue = pair.value(); if (annotationValue.value() instanceof AnnotationValue[]) { Annotatio...
java
public boolean shouldProfile(String url) { // Don't profile requests to to results servlet if (url.startsWith(servletURL)) { return false; } if (!restrictedURLs.isEmpty()) { boolean matches = false; for (Pattern p : restrictedURLs) { if (p.matcher(url).find()) ...
java
@Override protected void serializeTo(RawDataBuffer out) { super.serializeTo(out); out.writeInt(sessionId.asInt()); out.writeBoolean(transacted); out.writeInt(acknowledgeMode); }
python
def _make_the_call(self, method, url, body=None): """Note that a request response is being used here, not webob.""" self.log.debug("%s call to %s with body = %s" % (method, url, body)) params = {"url": url, "headers": self.headers, "verify": self.verify} if body is not None: ...
python
def read_data(self,variable_instance): """ read values from the device """ if self.inst is None: return vp_func = variable_instance.variableproperty_set.filter(name=':FUNC').first() measure_function = '' if vp_func: if vp_func.value(): ...
python
def _dens(self,R,z,phi=0.,t=0.): """ NAME: _dens PURPOSE: evaluate the density for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: the densi...
java
public org.modeshape.jcr.api.Problems backupRepository( File backupDirectory, BackupOptions options ) throws RepositoryException { // Create the activity ... final BackupActivity backupActivity = createBackupActivity(backupDirectory, options); //suspend any existing transactions try { ...
python
def is_type(obj, type_, **kwargs): """Indicate if ``obj`` is a type in ``type_``. .. hint:: This checker is particularly useful when you want to evaluate whether ``obj`` is of a particular type, but importing that type directly to use in :func:`isinstance() <python:is...
python
def libvlc_media_discoverer_media_list(p_mdis): '''Get media service discover media list. @param p_mdis: media service discover object. @return: list of media items. ''' f = _Cfunctions.get('libvlc_media_discoverer_media_list', None) or \ _Cfunction('libvlc_media_discoverer_media_list', ((1,...
python
def decode(self): """Hook to transform the response, called when this IOCB is completed.""" if _debug: IOChainMixIn._debug("decode") # refer to the chained iocb iocb = self.ioChain # if this has completed successfully, pass it up if self.ioState == COMPLETED: ...
python
def learn(self, examples, attributes, parent_examples): """ A decision tree learner that *strictly* follows the pseudocode given in AIMA. In 3rd edition, see Figure 18.5, page 702. """ if not examples: return self.plurality_value(parent_examples) elif len(set(...
python
def sequences_to_fixed_length_index_encoded_array( klass, sequences, left_edge=4, right_edge=4, max_length=15): """ Transform a sequence of strings, where each string is of length at least left_edge + right_edge and at most max_length into strings of length max_length using a...
python
def autobuild_onlycopy(): """Autobuild a project that does not require building firmware, pcb or documentation """ try: # Build only release information family = utilities.get_family('module_settings.json') autobuild_release(family) Alias('release', os.path.join('build', 'ou...
java
@CheckReturnValue public static CloudStorageFileSystem forBucket(String bucket, CloudStorageConfiguration config) { checkArgument( !bucket.startsWith(URI_SCHEME + ":"), "Bucket name must not have schema: %s", bucket); checkNotNull(config); return new CloudStorageFileSystem( new CloudStorag...
python
def sequence(self, per_exon=False): """ Return the sequence for this feature. if per-exon is True, return an array of exon sequences This sequence is never reverse complemented """ db = self.db if not per_exon: start = self.txStart + 1 retu...
python
def _call(self, x): """``self(x)``.""" with self.mutex: result = sheardec2D(x, self.shearlet_system) return np.moveaxis(result, -1, 0)
python
def flush(self): """ Sends buffered data to the target """ # Flush buffer line = self._buffer.getvalue() self._buffer = StringIO() # Send the message content = {"session_id": self._session, "text": line} self._herald.fire(self._peer, beans.Message...
java
public void marshall(ListInstanceFleetsRequest listInstanceFleetsRequest, ProtocolMarshaller protocolMarshaller) { if (listInstanceFleetsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(list...
python
def image_channel_embeddings_top(body_output, targets, model_hparams, vocab_size): """Top transformation for images.""" del targets # unused arg with tf.variable_scope("image_channel_embeddings_bottom"): img_le...
python
def status_for_all_orders(self): """Status for all orders https://starfighter.readme.io/docs/status-for-all-orders """ url_fragment = 'venues/{venue}/accounts/{account}/orders'.format( venue=self.venue, account=self.account, ) url = urljoin(self.b...
python
def inv_mix_columns(state): """ Transformation in the Inverse Cipher that is the inverse of MixColumns(). """ state = state.reshape(4, 4, 8) return fcat( multiply(IMA, state[0]), multiply(IMA, state[1]), multiply(IMA, state[2]), multiply(IMA, state[3]), )
java
public static PublishDelete createPublishDelete(Identifier i1, Identifier i2) { return createPublishDelete(i1, i2, null); }
python
def insert_child(self, child_pid, index=-1): """Insert a Version child PID.""" if child_pid.status != PIDStatus.REGISTERED: raise PIDRelationConsistencyError( "Version PIDs should have status 'REGISTERED'. Use " "insert_draft_child to insert 'RESERVED' draft P...
python
def get_all_runs(self, only_largest_budget=False): """ returns all runs performed Parameters ---------- only_largest_budget: boolean if True, only the largest budget for each configuration is returned. This makes sense if the runs are continued across budgets and the info field contains the info...
python
def split_pem(s): """ Split PEM objects. Useful to process concatenated certificates. """ pem_strings = [] while s != b"": start_idx = s.find(b"-----BEGIN") if start_idx == -1: break end_idx = s.find(b"-----END") end_idx = s.find(b"\n", end_idx) + 1 ...
python
def Nu_cylinder_Whitaker(Re, Pr, mu=None, muw=None): r'''Calculates Nusselt number for crossflow across a single tube as shown in [1]_ at a specified `Re` and `Pr`, both evaluated at the free stream temperature. Recommends a viscosity exponent correction of 0.25, which is applied only if provided. Also ...
python
def get_height(self, id=None, endpoint=None): """ Get the current height of the blockchain Args: id: (int, optional) id to use for response tracking endpoint: (RPCEndpoint, optional) endpoint to specify to use Returns: json object of the result or the...
java
public static long extractTimestampTiny(long idTiny) { final long blockSize = 10000L; final long threshold = 0x800000000L; long timestamp = idTiny > threshold ? idTiny >>> SHIFT_TIMESTAMP_TINY : idTiny; return timestamp * blockSize + TIMESTAMP_EPOCH; }
python
def index(advice): '''Index/Reindex a CADA advice''' topics = [] for topic in advice.topics: topics.append(topic) parts = topic.split('/') if len(parts) > 1: topics.append(parts[0]) try: es.index(index=es.index_name, doc_type=DOCTYPE, id=advice.id, body={ ...
java
public static Integer getDayOfMonth(Date date) { if (date == null) return null; Calendar calendar = Calendar.getInstance(); calendar.setTime(date); return calendar.get(Calendar.DAY_OF_MONTH); }
java
public static void writeIntegerToStart(final File f, final int num) throws IOException { final RandomAccessFile fixupFile = new RandomAccessFile(f, "rw"); fixupFile.writeInt(num); fixupFile.close(); }
java
public static BasicGalleryWrapper<GalleryAlbumWrapper, AlbumFile, String, AlbumFile> galleryAlbum(Activity activity) { return new GalleryAlbumWrapper(activity); }
java
public void marshall(DeploymentJob deploymentJob, ProtocolMarshaller protocolMarshaller) { if (deploymentJob == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(deploymentJob.getArn(), ARN_BINDING); ...
java
public CrawlElement click(String tagName) { checkNotRead(); Preconditions.checkNotNull(tagName, "Tag name cannot be null"); CrawlElement crawlTag = new CrawlElement(EventType.click, tagName.toUpperCase()); crawlElements.add(crawlTag); return crawlTag; }
python
def consume(self, word_id: int) -> 'AvoidState': """ Consumes a word, and updates the state based on it. Returns new objects on a state change. The next state for a word can be tricky. Here are the cases: (1) If the word is found in our set of outgoing child arcs, we take that transitio...
java
public boolean isGeometry(GeometryIndex index) { if (index.hasChild()) { return isGeometry(index.getChild()); } return index.getType() == GeometryIndexType.TYPE_GEOMETRY; }
java
private void _appendOptionGroup (final StringBuilder aSB, final OptionGroup aGroup) { if (!aGroup.isRequired ()) aSB.append ('['); final ICommonsList <Option> optList = aGroup.getAllOptions (); if (m_aOptionComparator != null) optList.sort (m_aOptionComparator); // for each option in the...
python
def update_issue_remote_link_by_id(self, issue_key, link_id, url, title, global_id=None, relationship=None): """ Update existing Remote Link on Issue :param issue_key: str :param link_id: str :param url: str :param title: str :param global_id: str, OPTIONAL: ...
python
def _check_date(self, fmt='%Y-%m-%d'): """Convenience method for determining if the input date is valid. Parameters ---------- fmt : str The format of the date string. The default is ``%Y-%m-%d``, which corresponds to ``YYYY-MM-DD``. Returns ----...
python
def cli(env, volume_id): """Display details for a specified volume.""" file_manager = SoftLayer.FileStorageManager(env.client) file_volume = file_manager.get_file_volume_details(volume_id) file_volume = utils.NestedDict(file_volume) table = formatting.KeyValueTable(['Name', 'Value']) table.alig...
java
public void removeChildren() { log.trace("removeChildren of {}", name); for (IBasicScope child : children.keySet()) { removeChildScope(child); } }
python
def normalize(vector): '''Normalizes the `vector` so that its length is 1. `vector` can have any number of components. ''' d = sum(x * x for x in vector) ** 0.5 return tuple(x / d for x in vector)
python
def GetNextNode(self, modes, innode): """GetNextNode returns the outnode that matches an element from the modes list, starting at the given innode. This method isnt actually used, its just a helper method for debugging purposes. """ nodes = N.where(self.innodes == innode...
python
def requestClaimDef(self, seqNo, signature, sender): """ Used to get a claim def from Sovrin :param seqNo: reference number of schema :param signature: CL is only supported option currently :return: req object """ operation = { TXN_TYPE: GET_CLAIM_DEF, ...
java
public Class getPersistentFieldClass() { if (m_persistenceClass == null) { Properties properties = new Properties(); try { this.logWarning("Loading properties file: " + getPropertiesFile()); properties.load(new FileInputStre...
java
public void setAveragingEnabled(final boolean ENABLED) { if (null == averagingEnabled) { _averagingEnabled = ENABLED; fireUpdateEvent(REDRAW_EVENT); } else { averagingEnabled.set(ENABLED); } }
java
public static void main(String[] args) { try { if (args.length != 4) { System.out.println("Usage: PrimaveraConvert <JDBC Driver Class> <JDBC connection string> <project ID> <output file name>"); } else { PrimaveraConvert convert = new P...
java
private void mergeTemplate(String templateFilename, File folder, String javaFilename, boolean overwrite) { final File javaFile = new File(folder, javaFilename); // create destination folder? File destinationFolder = javaFile.getParentFile(); if (false == destinationFo...
python
def _parse_time_to_freeze(time_to_freeze_str): """Parses all the possible inputs for freeze_time :returns: a naive ``datetime.datetime`` object """ if time_to_freeze_str is None: time_to_freeze_str = datetime.datetime.utcnow() if isinstance(time_to_freeze_str, datetime.datetime): ti...
java
public void setupFields() { FieldInfo field = null; field = new FieldInfo(this, ID, Constants.DEFAULT_FIELD_LENGTH, null, null); field.setDataClass(Integer.class); field.setHidden(true); field = new FieldInfo(this, LAST_CHANGED, Constants.DEFAULT_FIELD_LENGTH, null, null); ...
python
def convert_effsize(ef, input_type, output_type, nx=None, ny=None): """Conversion between effect sizes. Parameters ---------- ef : float Original effect size input_type : string Effect size type of ef. Must be 'r' or 'd'. output_type : string Desired effect size type. ...
java
public static netbridge_vlan_binding[] get(nitro_service service, String name) throws Exception{ netbridge_vlan_binding obj = new netbridge_vlan_binding(); obj.set_name(name); netbridge_vlan_binding response[] = (netbridge_vlan_binding[]) obj.get_resources(service); return response; }
java
public final double sampleMin() { long count = _acquireCount.get() - _releaseCount.get(); long min = _min.getAndSet(count); return min; }
python
def check_updates(transformers, datastore=None, stimuli=None): """ Run transformers through a battery of stimuli, and check if output has changed. Store results in csv file for comparison. Args: transformers (list): A list of tuples of transformer names and dictionary of parameters to i...
java
protected void copyFieldsFrom(RepositoryResourceImpl fromResource, boolean includeAttachmentInfo) { setName(fromResource.getName()); // part of the identification so locked setDescription(fromResource.getDescription()); setShortDescription(fromResource.getShortDescription()); setProvider...
java
public boolean hasPermissionsById(String id, String... permissions) { List<Permission> resolvedPermissions = Lists.newArrayListWithCapacity(permissions.length); for (String permission : permissions) { resolvedPermissions.add(getPermissionResolver().resolvePermission(permission)); } ...
java
public boolean addControlListener(String name, Widget.OnTouchListener listener) { Widget control = findChildByName(name); if (control != null) { return control.addTouchListener(listener); } return false; }
java
public boolean sameTypes(Schema schema) { if (schema.numColumns() != numColumns()) return false; for (int i = 0; i < schema.numColumns(); i++) { if (getType(i) != schema.getType(i)) return false; } return true; }
java
public OpenFalconBean build(String metric, Number value) { OpenFalconBean falconBean = initDefault(metric); falconBean.setValue(value); return falconBean; }
python
def _substitute_file_uuids_throughout_template(self, template, file_dependencies): """Anywhere in "template" that refers to a data object but does not give a specific UUID, if a matching file can be found in "file_dependencies", we will change the data object reference to use that UUID. That wa...
python
def _commandline(repositories, port=8000, host="127.0.0.1", debug=False, cache=None, cache_path="./cache", redis=None): """ Run a CTS API from command line. .. warning:: This function should not be used in the production context :param repositories: :param port: :...
python
def handle_get_scans_command(self, scan_et): """ Handles <get_scans> command. @return: Response string for <get_scans> command. """ scan_id = scan_et.attrib.get('scan_id') details = scan_et.attrib.get('details') pop_res = scan_et.attrib.get('pop_results') if det...
java
@Override public CreateVpcLinkResult createVpcLink(CreateVpcLinkRequest request) { request = beforeClientExecution(request); return executeCreateVpcLink(request); }
java
@GET @Path("search") @Consumes(Servlets.JSON_MEDIA_TYPE) @Produces(Servlets.JSON_MEDIA_TYPE) public Response search(@QueryParam("query") String query, @DefaultValue(LIMIT_OFFSET_DEFAULT) @QueryParam("limit") int limit, @DefaultValue(LIMIT_OFFSET_DEFA...
java
@Override public void error(VirtualConnection vc, TCPWriteRequestContext wsc, IOException ioe) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, "error, vc=" + getVCHash()); } // Nothing else needs to be done here. Report error up the chain. ...
python
def is_atlas_enabled(blockstack_opts): """ Can we do atlas operations? """ if not blockstack_opts['atlas']: log.debug("Atlas is disabled") return False if 'zonefiles' not in blockstack_opts: log.debug("Atlas is disabled: no 'zonefiles' path set") return False if...