language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def get_repo_hooks(self, auth, username, repo_name): """ Returns all hooks of repository with name ``repo_name`` owned by the user with username ``username``. :param auth.Authentication auth: authentication object :param str username: username of owner of repository :par...
python
def make_connection(transport, **kwargs): """ Creates a connection instance based on the transport This function creates the EapiConnection object based on the desired transport. It looks up the transport class in the TRANSPORTS global dictionary. Args: transport (string): The transport t...
python
def remove_jobs(self, mask): """Mark all jobs that match a mask as 'removed' """ jobnames = self.table[mask]['jobname'] jobkey = self.table[mask]['jobkey'] self.table[mask]['status'] = JobStatus.removed for jobname, jobkey in zip(jobnames, jobkey): fullkey = JobDetail...
python
def create_from_response_pdu(resp_pdu): """ Create instance from response PDU. :param resp_pdu: Byte array with request PDU. :return: Instance of :class:`WriteSingleRegister`. """ write_single_register = WriteSingleRegister() address, value = struct.unpack('>H' + conf.T...
python
def _validate(self, writing=False): """Self-validate the box before writing.""" box_ids = [box.box_id for box in self.box] if len(box_ids) != 1 or box_ids[0] != 'flst': msg = ("Fragment table boxes must have a single fragment list " "box as a child box.") ...
python
def show(cobertura_file, format, output, source, source_prefix): """show coverage summary of a Cobertura report""" cobertura = Cobertura(cobertura_file, source=source) Reporter = reporters[format] reporter = Reporter(cobertura) report = reporter.generate() if not isinstance(report, bytes): ...
java
protected final void applyIndexedTagId(AbstractHtmlState state, String tagId) throws JspException { state.id = indexTagId(generateTagId(tagId)); }
python
def to_primitive(self, load_rels=None, sparse_fields=None, *args, **kwargs): """ Override the schematics native to_primitive method :param loads_rels: List of field names that are relationships that should be loaded for the serialization process. This needs ...
java
public EClass getIfcLightSourceAmbient() { if (ifcLightSourceAmbientEClass == null) { ifcLightSourceAmbientEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(294); } return ifcLightSourceAmbientEClass; }
python
async def handle_request(self, request): """Respond to request if PIN is correct.""" service_name = request.rel_url.query['servicename'] received_code = request.rel_url.query['pairingcode'].lower() _LOGGER.info('Got pairing request from %s with code %s', service_name...
python
def _wipe_www_page(self, slug): '''Remove all data in www about the page identified by slug.''' wd = os.path.join(self._dirs['www'], slug) if os.path.isdir(wd): # pragma: no cover shutil.rmtree(wd)
java
public void addUUID( long lo, long hi ) { if (C16Chunk.isNA(lo, hi)) { addNA(); return; } if( _ms==null || _ds== null || _sparseLen >= _ms.len() ) append2slowUUID(); _ms.set(_sparseLen,lo); _ds[_sparseLen] = Double.longBitsToDouble(hi); if (_id != null) _id[_sparseLen] = _len; ...
python
def elaborate(self, top_def_name=None, inst_name=None, parameters=None): """ Elaborates the design for the given top-level addrmap component. During elaboration, the following occurs: - An instance of the ``$root`` meta-component is created. - The addrmap component specified by...
python
def generate_page(self, path, template, **kwargs): """ Generate the HTML for a single page. You usually don't need to call this method manually, it is used by a lot of other, more end-user friendly methods. Args: path (str): Where to place the page relative to the root URL. Usually something like "...
python
def _get_chunk_edges(self, NN, chunk_size, chunk_overlap): """ Given the size of the array, calculate and array that gives the edges of chunks of nominal size, with specified overlap Parameters ---------- NN : int Size of array chunk_size : int ...
java
public void init(Record record, String strLinkedRecord, int iFieldSeq) { super.init(null); m_MergeRecord = record; m_strLinkedRecord = strLinkedRecord; m_FieldSeq = iFieldSeq; if (record != null) record.addListener(new RemoveConverterOnCloseHandler(this)); // B...
java
public static LocalDateTime now(Clock clock) { Jdk8Methods.requireNonNull(clock, "clock"); final Instant now = clock.instant(); // called once ZoneOffset offset = clock.getZone().getRules().getOffset(now); return ofEpochSecond(now.getEpochSecond(), now.getNano(), offset); }
java
protected static double gammaCdf(double x, double a) { if(x<0) { throw new IllegalArgumentException("The x parameter must be positive."); } double GI; if (a>200) { double z=(x-a)/Math.sqrt(a); double y=gaussCdf(z); double b1=2/Math...
java
public void restart() { for (InputVariable inputVariable : this.inputVariables) { inputVariable.setValue(Double.NaN); } for (OutputVariable outputVariable : this.outputVariables) { outputVariable.clear(); } }
java
public void delete(String name) throws IOException { if (name.equalsIgnoreCase(SKIP_CERTS)) throw new IOException("Attribute " + SKIP_CERTS + " may not be deleted."); else throw new IOException("Attribute name not recognized by " + ...
python
def setup(self, builder): """Performs this component's simulation setup and return sub-components. Parameters ---------- builder : `engine.Builder` Interface to several simulation tools including access to common random number generation, in particular. ...
java
public void copy(ConnectionContext source) { this.connection = source.connection; this.session = source.session; this.destination = source.destination; }
java
public List<Double> x() { List<Double> result = new ArrayList<Double>(xy.size()); for (Discrete.Pair pair : xy) { result.add(pair.x); } return result; }
python
def disqus_show_comments(context, shortname=''): """ Return the HTML code to display DISQUS comments. """ shortname = getattr(settings, 'DISQUS_WEBSITE_SHORTNAME', shortname) return { 'shortname': shortname, 'config': get_config(context), }
python
def print(root): # type: (Union[Nonterminal,Terminal,Rule])-> str """ Transform the parsed tree to the string. Expects tree like structure. You can see example output below. (R)SplitRules26 |--(N)Iterate | `--(R)SplitRules30 | `--(N)Symb | ...
python
def _get_primary_index_in_altered_table(self, diff): """ :param diff: The table diff :type diff: orator.dbal.table_diff.TableDiff :rtype: dict """ primary_index = {} for index in self._get_indexes_in_altered_table(diff).values(): if index.is_primary(...
java
public List<Path> calcPaths(GHRequest request, GHResponse ghRsp) { if (ghStorage == null || !fullyLoaded) throw new IllegalStateException("Do a successful call to load or importOrLoad before routing"); if (ghStorage.isClosed()) throw new IllegalStateException("You need to create...
java
public <T> T callFunction( final String name, final List<?> args, final @Nullable Long requestTimeout, final Decoder<T> decoder) { return this.functionService.callFunction(name, args, requestTimeout, decoder); }
python
def Sphere(radius=0.5, center=(0, 0, 0), direction=(0, 0, 1), theta_resolution=30, phi_resolution=30, start_theta=0, end_theta=360, start_phi=0, end_phi=180): """ Create a vtk Sphere Parameters ---------- radius : float, optional Sphere radius center : np.ndarray or list, op...
python
def _cellMask(self, index): """ Returns the data mask of the cell at the index (without any string conversion) """ row = index.row() col = index.column() if (row < 0 or row >= self.rowCount() or col < 0 or col >= self.columnCount()): return None # The check a...
java
public String getString(String name) { return decryptValue((String)get(name, PropType.string)); }
java
public <T> ESDatas<T> searchAllParallel(String index, int fetchSize ,Class<T> type,int thread) throws ElasticSearchException{ return searchAllParallel(index, fetchSize,(ScrollHandler<T>)null,type,thread); }
java
private void cleanConditionally(Element e, String tag) { Elements tagsList = getElementsByTag(e, tag); /** * Gather counts for other typical elements embedded within. Traverse * backwards so we can remove nodes at the same time without effecting * the traversal. * ...
java
public static boolean checkTimeInRangeWithSkew(Date timeToCheck, Date startDate, Date endDate, int skewInMinutes) { if (startDate.after(endDate) || startDate.equals(endDate)) { String msg = String .format( "Illegal time interval: start date must be before end date. [start date: %s, end ...
java
public Map<String, String> completeByFeature(PCM pcm, String ftName) throws Exception { Map<String, String> ftNames2Images = new HashMap<>(); List<Feature> fts = pcm.getConcreteFeatures(); Feature ft = null; for (Feature feature : fts) { if (feature.getName().equals(ftName)) { ft = feature; bre...
python
def day(self, num): """Return the given day of week as a date object. Day 0 is the Monday.""" d = date(self.year, 1, 4) # The Jan 4th must be in week 1 according to ISO return d + timedelta(weeks=self.week-1, days=-d.weekday() + num)
java
public void setViewPager(ViewPagerEx pager){ if(pager.getAdapter() == null){ throw new IllegalStateException("Viewpager does not have adapter instance"); } mPager = pager; mPager.addOnPageChangeListener(this); ((InfinitePagerAdapter)mPager.getAdapter()).getRealAdapter...
python
def _read_file_header(self): """Reads out the file header for the arc file. If version was not provided, this will autopopulate it.""" header = self.fileobj.readline() payload1 = self.fileobj.readline() payload2 = self.fileobj.readline() version, reserved, organisation = ...
java
public int lengthOf(String value) { int length = 0; if (value != null) { length = value.length(); } return length; }
python
def removeNestedGroups(node): """ This walks further and further down the tree, removing groups which do not have any attributes or a title/desc child and promoting their children up one level """ global _num_elements_removed num = 0 groupsToRemove = [] # Only consider <g> elements ...
python
def nlmsg_convert(hdr): """Convert a Netlink message received from a Netlink socket to an nl_msg. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L382 Allocates a new Netlink message and copies all of the data in `hdr` into the new message object. Positional arguments: hdr -- Netlink ...
python
def to_digestable(self, origin=None): """Convert name to a format suitable for digesting in hashes. The name is canonicalized and converted to uncompressed wire format. @param origin: If the name is relative and origin is not None, then origin will be appended to it. @type orig...
python
def is_correct(self): # pylint: disable=too-many-branches """Check if this object configuration is correct :: * Check our own specific properties * Call our parent class is_correct checker :return: True if the configuration is correct, otherwise False :rtype: bool ...
java
public Observable<Page<InterfaceEndpointInner>> listAsync() { return listWithServiceResponseAsync() .map(new Func1<ServiceResponse<Page<InterfaceEndpointInner>>, Page<InterfaceEndpointInner>>() { @Override public Page<InterfaceEndpointInner> call(ServiceResponse<Page<...
python
def get_content(self, key): """ Gets given content from the cache. Usage:: >>> cache = Cache() >>> cache.add_content(John="Doe", Luke="Skywalker") True >>> cache.get_content("Luke") 'Skywalker' :param key: Content to retrieve...
java
public Address add(Address address) { // if address is null or is the root address then there is nothing to append if (address == null || address.isRoot()) { return this; } // if we are the root address then the given address just is our new address, // otherwise, ap...
java
protected void setChangedInLastRequest(final boolean changed) { if (isChangedInLastRequest() != changed) { InputModel model = getOrCreateComponentModel(); model.changedInLastRequest = changed; } }
python
def send_results(self, result): """ Upload a result object to server. If resultConverter has been provided, use it to convert result object to format accepted by the server. If needed, use testcase_converter to convert tc metadata in result to suitable format. returns ne...
java
@RequestMapping(value = "api/group/{groupId}", method = RequestMethod.DELETE) public @ResponseBody List<Group> removeGroup(Model model, @PathVariable int groupId) { pathOverrideService.removeGroup(groupId); return pathOverrideService.findAllGroups(); }
python
def rdf_iterator(graph, lang, add_vtype=False): """ Convert a Graph response into a double iterable, by triples and elements. Optionally add element type, and filter triples by language (on literals) """ # Return the header row hdr = ('subject', 'predicate', 'object') yield hdr if not add_vt...
java
protected Component newTitle(final String titleId, final IModel<?> titleModel, final int index) { return new Label(titleId, titleModel); }
java
public void setTTLParam(int ttl) { try { getSipURI().setTTLParam(ttl); super.parameters.put(TTL, "" + ttl); } catch (InvalidArgumentException e) { logger.error("invalid argument", e); } }
python
def clipped_area(ts, thresh=0, integrator=integrate.trapz): """Total value * time above the starting value within a TimeSeries Arguments: ts (pandas.Series): Time series to be integrated. thresh (float): Value to clip the tops off at (crossings will be interpolated) References: http://nb...
java
@Override public ByteArray readByteArray() { int type = readInteger(); if ((type & 1) == 0) { return (ByteArray) getReference(type >> 1); } type >>= 1; ByteArray result = new ByteArray(buf, type); storeReference(result); return result; ...
java
public StringExpression substring(Expression<Integer> beginIndex, Expression<Integer> endIndex) { return Expressions.stringOperation(Ops.SUBSTR_2ARGS, mixin, beginIndex, endIndex); }
java
public static int writeShorts(final BitOutput bitOutput, final int lengthSize, final int shortSize, final short[] value) throws IOException { if (bitOutput == null) { throw new NullPointerException("bitOutput is null"); } requireValidSize...
python
def _ParseEntryObjectOffsets(self, file_object, file_offset): """Parses entry array objects for the offset of the entry objects. Args: file_object (dfvfs.FileIO): a file-like object. file_offset (int): offset of the first entry array object relative to the start of the file-like object. ...
java
private List<CmsSearchIndexSource> searchIndexSources() { CmsSearchManager manager = OpenCms.getSearchManager(); I_CmsSearchIndex index = manager.getIndex(getParamIndexName()); List<CmsSearchIndexSource> sources = index.getSources(); return sources; }
python
def get_list_key(self, data, key, header_lines=1): """Get the list of a key elements. Each element is a tuple (key=None, description, type=None). Note that the tuple's element can differ depending on the key. :param data: the data to proceed :param key: the key """ ...
java
public ClassGraph whitelistClasspathElementsContainingResourcePath(final String... resourcePaths) { for (final String resourcePath : resourcePaths) { final String resourcePathNormalized = WhiteBlackList.normalizePath(resourcePath); scanSpec.classpathElementResourcePathWhiteBlackList.addT...
python
def get_csv_from_json(d): """ Get CSV values when mixed into json data. Pull out the CSV data and put it into a dictionary. :param dict d: JSON with CSV values :return dict: CSV values. (i.e. { CSVFilename1: { Column1: [Values], Column2: [Values] }, CSVFilename2: ... } """ logger_jsons.info("ent...
java
protected void computeMappingsFromObject( MtasTokenIdFactory mtasTokenIdFactory, MtasParserObject object, Map<String, List<MtasParserObject>> currentList, Map<String, Map<Integer, Set<String>>> updateList) throws MtasParserException, MtasConfigException { MtasParserType<MtasParserMapping<?>>...
python
def get_tokens(text, encoding=None): """ Return an iterable of (tokentype, value) pairs generated from `text`. If `unfiltered` is set to `True`, the filtering mechanism is bypassed even if filters are defined. Also preprocess the text, i.e. expand tabs and strip it if wa...
java
public OvhTaskMl domain_mailingList_POST(String domain, OvhDomainMlLanguageEnum language, String name, OvhDomainMlOptionsStruct options, String ownerEmail, String replyTo) throws IOException { String qPath = "/email/domain/{domain}/mailingList"; StringBuilder sb = path(qPath, domain); HashMap<String, Object>o = n...
java
public ServiceFuture<Void> deleteFaceAsync(String faceListId, UUID persistedFaceId, final ServiceCallback<Void> serviceCallback) { return ServiceFuture.fromResponse(deleteFaceWithServiceResponseAsync(faceListId, persistedFaceId), serviceCallback); }
python
def getWorkingSeatedZeroPoseToRawTrackingPose(self): """Returns the preferred seated position from the working copy.""" fn = self.function_table.getWorkingSeatedZeroPoseToRawTrackingPose pmatSeatedZeroPoseToRawTrackingPose = HmdMatrix34_t() result = fn(byref(pmatSeatedZeroPoseToRawTrack...
java
private static void honorVerboseFlag(final ArgP argp) { if (argp.optionExists("--verbose") && !argp.has("--verbose") && !argp.has("-v")) { // SLF4J doesn't provide any API to programmatically set the logging // level of the underlying logging library. So we have to violate the // encapsul...
java
@Override public Iterator<Entry<K, V>> iterator() { return new Iterator<Entry<K, V>>() { private final Entry<K, V>[] tab = KeyMap.this.table; private Entry<K, V> nextEntry; private int nextPos = 0; @Override public boolean hasNext() { if (nextEntry != null) { return true; } else {...
python
def _validate_params(priors, means, covars): """ Validation Check for M.L. paramateres """ for i,(p,m,cv) in enumerate(zip(priors, means, covars)): if np.any(np.isinf(p)) or np.any(np.isnan(p)): raise ValueError("Component %d of priors is not valid " % i) if np.any(np.isinf(m))...
java
public GsonXml create() { if (coreBuilder == null) { coreBuilder = new GsonBuilder(); } return new GsonXml(coreBuilder.create(), xmlParserCreator, options); }
python
def from_env(cls, **kwargs): """ Return a client configured from environment variables. The environment variables used are the same as those used by the Docker command-line client. They are: .. envvar:: DOCKER_HOST The URL to the Docker host. .. envvar:: D...
java
public ApiResponse<CloudUserDetails> getInfo1WithHttpInfo(String authorization) throws ApiException { com.squareup.okhttp.Call call = getInfo1ValidateBeforeCall(authorization, null, null); Type localVarReturnType = new TypeToken<CloudUserDetails>(){}.getType(); return apiClient.execute(call, loc...
java
@Override public synchronized void close() { try { for (final PreparedStatementCapsule preparedStatement : stmts.values()) { try { preparedStatement.ps.close(); } catch (final SQLException e) { logger.warn("Could not close ...
java
public void insertWith(int insertPosition, List<BaseCell> list) { int newItemSize = list != null ? list.size() : 0; if (newItemSize > 0 && mGroupBasicAdapter != null) { if (insertPosition >= mGroupBasicAdapter.getItemCount()) { insertPosition = mGroupBasicAdapter.getItemCount...
java
public static Date parseToDateLenient(final String date, final String format, final boolean lenient) { if (date == null || format == null || format.length() <= 0) { return null; } final DateFormat df = new SimpleDateFormat(format); df.setLenient(lenient); Date parsedDate = null; try { parsedDat...
java
public final Object put2d(Object key1, Object key2, Object value) { AssociativeArray tmp = internalData.get(key1); if(tmp == null) { internalData.put(key1, new AssociativeArray()); } return internalData.get(key1).internalData.put(key2, value); }
python
def make_value_from_shell(self, param, value_type, function): """ run command in the shell """ try: value = check_output(param, shell=True).rstrip() except CalledProcessError: # for value_type of 'bool' we return False on error code if value_ty...
java
public DocumentPath parent() { if (pathElements.size() <= 1) { return null; } return new DocumentPath(this.pathElements.subList(0, pathElements.size() - 1)); }
java
@GET @Path("protocols") public Map<String, ProtocolInfo> getProtocols() throws GuacamoleException { // Get and return a map of all protocols. Environment env = new LocalEnvironment(); return env.getProtocols(); }
python
def request(self, method, uri, params=None, data=None, headers=None, auth=None, timeout=None, allow_redirects=False): """ Make an HTTP request. """ url = self.relative_uri(uri) return self.domain.request( method, url, params=par...
java
public static ns_clusternode remove_node(nitro_service client, ns_clusternode resource) throws Exception { return ((ns_clusternode[]) resource.perform_operation(client, "remove_node"))[0]; }
java
public JobRequest addParameter(String key, String value) { validateParameter(key, value); parameters.put(key, value); return this; }
java
public void setIpV4Addresses(java.util.Collection<String> ipV4Addresses) { if (ipV4Addresses == null) { this.ipV4Addresses = null; return; } this.ipV4Addresses = new java.util.ArrayList<String>(ipV4Addresses); }
java
@Override public boolean setA(DMatrixRMaj A) { blockA.reshape(A.numRows,A.numCols,false); MatrixOps_DDRB.convert(A,blockA); return alg.setA(blockA); }
java
public void marshall(DeleteContactRequest deleteContactRequest, ProtocolMarshaller protocolMarshaller) { if (deleteContactRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(deleteContactReques...
java
protected void doReadObject(final ObjectInputStream stream) throws IOException, ClassNotFoundException { final GetField readFields = stream.readFields(); for (final String fieldName : getFieldNamesInAdditionToId()) { final Object value = readFields.get(fieldName, null); setField...
python
def as_html(self, max_rows=0): """Format table as HTML.""" if not max_rows or max_rows > self.num_rows: max_rows = self.num_rows omitted = max(0, self.num_rows - max_rows) labels = self.labels lines = [ (0, '<table border="1" class="dataframe">'), ...
java
public void add(GSSName aName, int initLifetime, int acceptLifetime, Oid mech, int usage) throws GSSException { // currently we are not supporting multiple mechanism // credentials throw new GSSException(GSSException.UNAVAILABLE); }
java
public void setLcdCrystalEnabled(final boolean ENABLED) { if (null == lcdCrystalEnabled) { _lcdCrystalEnabled = ENABLED; fireUpdateEvent(VISIBILITY_EVENT); } else { lcdCrystalEnabled.set(ENABLED); } }
java
public static aaauser_vpntrafficpolicy_binding[] get(nitro_service service, String username) throws Exception{ aaauser_vpntrafficpolicy_binding obj = new aaauser_vpntrafficpolicy_binding(); obj.set_username(username); aaauser_vpntrafficpolicy_binding response[] = (aaauser_vpntrafficpolicy_binding[]) obj.get_resou...
java
public Observable<VirtualMachineCaptureResultInner> beginCaptureAsync(String resourceGroupName, String vmName, VirtualMachineCaptureParameters parameters) { return beginCaptureWithServiceResponseAsync(resourceGroupName, vmName, parameters).map(new Func1<ServiceResponse<VirtualMachineCaptureResultInner>, Virtual...
java
public void setFlows(java.util.Collection<ListedFlow> flows) { if (flows == null) { this.flows = null; return; } this.flows = new java.util.ArrayList<ListedFlow>(flows); }
python
def main(): """ NAME b_vdm.py DESCRIPTION converts B (in microT) and (magnetic) latitude to V(A)DM INPUT (COMMAND LINE ENTRY) B (microtesla), latitude (positive north) OUTPUT V[A]DM SYNTAX b_vdm.py [command line options] [< filename] ...
python
def max(self): """Get maximum target value found and corresponding parametes.""" try: res = { 'target': self.target.max(), 'params': dict( zip(self.keys, self.params[self.target.argmax()]) ) } except Valu...
python
def setComment(self, msg): """Sets the widget text to *msg* :param msg: overwrites any existing text with *msg* :type msg: str """ self.ui.commentTxtedt.setPlainText(msg) # move text cursor to end self.ui.commentTxtedt.moveCursor(QtGui.QTextCursor.End)
python
def dispatch_with_args(self, body, argMap): 'Perform callback dispatching, with enhanced arguments and recording of response' inputs = body.get('inputs', []) state = body.get('state', []) output = body['output'] try: output_id = output['id'] output_proper...
python
async def get(self, path, **query): '''return a get request Parameters ---------- path : str same as get_url query : kargs dict additional info to pass to get_url See Also -------- get_url : getJson : Returns ------- requests.models.Response the r...
python
def update(self): """Update the battery state.""" self._controller.update(self._id, wake_if_asleep=False) data = self._controller.get_charging_params(self._id) if data: self.__battery_level = data['battery_level'] self.__charging_state = data['charging_state']
python
def make_dir(fname): """ Create the directory of a fully qualified file name if it does not exist. :param fname: File name :type fname: string Equivalent to these Bash shell commands: .. code-block:: bash $ fname="${HOME}/mydir/myfile.txt" $ dir=$(dirname "${fname}") ...
java
public IntronSequence addIntron(AccessionID accession, int begin, int end) throws Exception { if (intronSequenceHashMap.containsKey(accession.getID())) { throw new Exception("Duplicate accesion id " + accession.getID()); } intronAdded = true; IntronSequence intronSequence = new IntronSequence(this, begin, en...