language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public boolean quotesRequired(final String csvColumn, final CsvContext context, final CsvPreference preference) { return columnNumbers.contains(context.getColumnNumber()); }
python
def is_dicom(filename): '''returns Boolean of whether the given file has the DICOM magic number''' try: with open(filename) as f: d = f.read(132) return d[128:132]=="DICM" except: return False
java
@Nullable public VATCountryData getVATCountryData (@Nonnull final Locale aLocale) { ValueEnforcer.notNull (aLocale, "Locale"); final Locale aCountry = CountryCache.getInstance ().getCountry (aLocale); return m_aVATItemsPerCountry.get (aCountry); }
java
public static void combineWlpAndRaXmls(final String adapterName, RaConnector raConnector, WlpRaConnector wlpRaConnector) throws InvalidPropertyException, UnavailableException { raConnector.copyWlpSettings(wlpRaConnector); WlpRaResourceAdapter wlpResourceAdapter = wlpRaConnector.getResourceAdapter(); ...
python
def from_iso_datetime(datetimestring, use_dateutil=True): """Parse an ISO8601-formatted datetime string and return a datetime object. Use dateutil's parser if possible and return a timezone-aware datetime. """ if not _iso8601_datetime_re.match(datetimestring): raise ValueError('Not a valid ISO8...
python
def main(): """ NAME plotdi_e.py DESCRIPTION plots equal area projection from dec inc data and cones of confidence (Fisher, kent or Bingham or bootstrap). INPUT FORMAT takes dec/inc as first two columns in space delimited file SYNTAX plotdi_e.py [command li...
java
@Override public int read(SegmentIndexBuffer sib, File sibFile) throws IOException { check(sibFile); RandomAccessFile raf = new RandomAccessFile(sibFile, "r"); FileChannel channel = raf.getChannel(); readVersion(channel); int length = sib.read(channel); ...
java
public String substringData(int offset, int count) throws DOMException { if ((offset < 0) || (count < 0)) { throw new DOMException(DOMException.INDEX_SIZE_ERR, null); } String data = getData(); if (offset > data.length()) { throw new DOMException(DOMException.INDE...
python
def batch_size(self, batch_size): """Limits the number of documents returned in one batch. Each batch requires a round trip to the server. It can be adjusted to optimize performance and limit data transfer. .. note:: batch_size can not override MongoDB's internal limits on the ...
java
protected static Charset getCharset(final Map<String, String> properties) { String charsetName = properties.get("charset"); try { return charsetName == null ? Charset.defaultCharset() : Charset.forName(charsetName); } catch (IllegalArgumentException ex) { InternalLogger.log(Level.ERROR, "Invalid charset: " ...
java
public DataSetIterator getTrainIterator() { return new DataSetIterator() { @Override public DataSet next(int i) { throw new UnsupportedOperationException(); } @Override public List<String> getLabels() { return backedIte...
python
def has_privileged_access(executable): """ Check if an executable have the right to attach to Ethernet and TAP adapters. :param executable: executable path :returns: True or False """ if sys.platform.startswith("win"): # do not check anything on Windows ...
python
def append(self, cls, infer_hidden: bool = False, **kwargs) -> Encoder: """ Extends sequence with new Encoder. 'dtype' gets passed into Encoder instance if not present in parameters and supported by specific Encoder type. :param cls: Encoder type. :param infer_hidden: If number ...
python
def visit_Name(self, node: ast.Name) -> Any: """Load the variable by looking it up in the variable look-up and in the built-ins.""" if not isinstance(node.ctx, ast.Load): raise NotImplementedError("Can only compute a value of Load on a name {}, but got context: {}".format( no...
java
public Observable<Page<RedisResourceInner>> listNextAsync(final String nextPageLink) { return listNextWithServiceResponseAsync(nextPageLink) .map(new Func1<ServiceResponse<Page<RedisResourceInner>>, Page<RedisResourceInner>>() { @Override public Page<RedisResourceInne...
java
public void stroke(Canvas canvas, Align align, float x, float y) { float sy = y + bounds.y(); for (TextLayout line : lines) { float sx = x + bounds.x() + align.getX(line.width(), textWidth()); canvas.strokeText(line, sx, sy); sy += line.ascent() + line.descent() + line.leading(); } }
java
@Override public synchronized void resolve(JingleSession session) throws XMPPException, SmackException, InterruptedException { this.setResolveInit(); for (TransportCandidate candidate : this.getCandidatesList()) { if (candidate instanceof ICECandidate) { ICECandidate ice...
java
public static <T extends Comparable<? super T>> List<T> sortInplace(List<T> list) { Collections.sort(list); return list; }
python
def rewind(self): '''rewind to start''' self._index = 0 self.percent = 0 self.messages = {} self._flightmode_index = 0 self._timestamp = None self.flightmode = None self.params = {}
java
public void warnf(String format, Object... params) { doLogf(Level.WARN, FQCN, format, params, null); }
python
def execute(self, input_data): ''' Okay this worker is going build graphs from PCAP Bro output logs ''' # Grab the Bro log handles from the input bro_logs = input_data['pcap_bro'] # Weird log if 'weird_log' in bro_logs: stream = self.workbench.stream_sample(bro_logs...
java
private void writeObject(java.io.ObjectOutputStream out) throws IOException { if (delegateMethods != null) { delegateMethods.clear(); } out.defaultWriteObject(); }
java
public IfcMedicalDeviceTypeEnum createIfcMedicalDeviceTypeEnumFromString(EDataType eDataType, String initialValue) { IfcMedicalDeviceTypeEnum result = IfcMedicalDeviceTypeEnum.get(initialValue); if (result == null) throw new IllegalArgumentException( "The value '" + initialValue + "' is not a valid enum...
java
private void processXMLResourceEnvRefs(List<? extends ResourceEnvRef> resourceEnvRefs) throws InjectionException { for (ResourceEnvRef resourceEnvRef : resourceEnvRefs) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, "pr...
java
public void fieldsToControls() { super.fieldsToControls(); for (int iRowIndex = 0; iRowIndex < m_vComponentCache.size(); iRowIndex++) { ComponentCache componentCache = (ComponentCache)m_vComponentCache.elementAt(iRowIndex); if (componentCache != null) { ...
python
def detect_version(basedir, compiler=None, **compiler_attrs): """Compile, link & execute a test program, in empty directory `basedir`. The C compiler will be updated with any keywords given via setattr. Parameters ---------- basedir : path The location where the test program will be compi...
python
def set(self, name, value): """ Set the I{value} of a property by I{name}. The value is validated against the definition and set to the default when I{value} is None. @param name: The property name. @type name: str @param value: The new property value. @ty...
python
def _set_routing_system(self, v, load=False): """ Setter method for routing_system, mapped from YANG variable /routing_system (container) If this variable is read-only (config: false) in the source YANG file, then _set_routing_system is considered as a private method. Backends looking to populate th...
java
public static RepeatTests repeatDefault(String server) { return RepeatTests.with(mp20Features(server)) .andWith(ft20Features(server)); }
java
private static void scatter(SparseVector v, double[] z) { int[] index = v.getIndex(); int used = v.getUsed(); double[] data = v.getData(); Arrays.fill(z, 0); for (int i = 0; i < used; ++i) z[index[i]] = data[i]; }
python
def fmt_account(account, title=None): """Format an Account or a DirectedAccount.""" if title is None: title = account.__class__.__name__ # `Account` or `DirectedAccount` title = '{} ({} causal link{})'.format( title, len(account), '' if len(account) == 1 else 's') body = '' body +...
java
public void addListener(KeyMatcher matcher, VehicleMessage.Listener listener) { Log.i(TAG, "Adding listener " + listener + " to " + matcher); mNotifier.register(matcher, listener); }
python
def encrypters(self): """A ``set`` containing all key ids (if any) to which this message was encrypted.""" return set(m.encrypter for m in self._sessionkeys if isinstance(m, PKESessionKey))
python
def _convert(x, factor1, factor2): """ Converts mixing ratio x in comp1 - comp2 tie line to that in c1 - c2 tie line. Args: x (float): Mixing ratio x in comp1 - comp2 tie line, a float between 0 and 1. factor1 (float): Compositional ratio between ...
python
def _set_vrrp_rbridge_global(self, v, load=False): """ Setter method for vrrp_rbridge_global, mapped from YANG variable /vrrp_rbridge_global (container) If this variable is read-only (config: false) in the source YANG file, then _set_vrrp_rbridge_global is considered as a private method. Backends lo...
python
def _raise_exception(cls, reason, data=None): """ Raise aiohttp exception and pass payload/reason into it. """ text_dict = { "error": reason } if data is not None: text_dict["errors"] = data raise cls( text=json.dumps(text_dict), content_type="application/js...
python
def probePlane(img, origin=(0, 0, 0), normal=(1, 0, 0)): """ Takes a ``vtkImageData`` and probes its scalars on a plane. .. hint:: |probePlane| |probePlane.py|_ """ plane = vtk.vtkPlane() plane.SetOrigin(origin) plane.SetNormal(normal) planeCut = vtk.vtkCutter() planeCut.SetInputDa...
java
public boolean startSession() { synchronized (sharedLock) { SessionData session = loadSession(); if (isSessionActive(session)) { sharedLock.notifyAll(); return false; } else { clearAll(); } sharedLock.no...
java
public void setCaseValue(com.google.api.ads.adwords.axis.v201809.cm.ProductDimension caseValue) { this.caseValue = caseValue; }
java
Map<String, Object> getCopyOfProperties() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "getCopyOfProperties"); Map<String, Object> temp = null; // Make sure no-one changes the properties underneath us. synchronized (properties) { ...
java
private BigDecimal getSunTrueLongitude(BigDecimal meanAnomaly) { BigDecimal sinMeanAnomaly = new BigDecimal(Math.sin(convertDegreesToRadians(meanAnomaly).doubleValue())); BigDecimal sinDoubleMeanAnomaly = new BigDecimal(Math.sin(multiplyBy(convertDegreesToRadians(meanAnomaly), BigDecimal.valueOf(2)) ...
java
public double getDoubleProperty(final String name, final double defaultValue) { final String prop = getStringProperty(name); if (prop != null) { try { return Double.parseDouble(prop); } catch (final Exception ignored) { return defaultValue; ...
python
def create_states_geo_zone(cls, states_geo_zone, **kwargs): """Create StatesGeoZone Create a new StatesGeoZone This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_states_geo_zone(states_geo...
python
def up_by_name(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR, count=1): """Sync files whose filename attribute is highest in alphanumeric order""" remote_files = command.map_files_raw(remote_dir=remote_dir) local_files = list_local_files(*filters, local_dir=local_dir) greatest = sorted(local_fi...
java
public static ResourceReference getJQueryResourceReference() { ResourceReference reference; if (Application.exists()) { reference = Application.get().getJavaScriptLibrarySettings().getJQueryReference(); } else { reference = JQueryResourceReference.get(); } return reference; }
java
@Override public void onInitializeAccessibilityNodeInfo(@NonNull AccessibilityNodeInfo info) { super.onInitializeAccessibilityNodeInfo(info); if (Build.VERSION.SDK_INT >= 21) { info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_SCROLL_BACKWARD); info.addAction(Ac...
python
def get_speaker_volume(self): """Return the volume setting of the speaker.""" if not self.camera_extended_properties: return None speaker = self.camera_extended_properties.get('speaker') if not speaker: return None return speaker.get('volume')
python
def find_discordant_snps( self, individual1, individual2, individual3=None, save_output=False ): """ Find discordant SNPs between two or three individuals. Parameters ---------- individual1 : Individual reference individual (child if `individual2` and `individual...
python
def encrypt_file(src, dest, csv_keys): """Encrypt a file with the specific GPG keys and write out to the specified path""" keys = massage_keys(csv_keys.split(',')) cryptorito.encrypt(src, dest, keys)
python
def print_brokers(cluster_config, brokers): """Print the list of brokers that will be restarted. :param cluster_config: the cluster configuration :type cluster_config: map :param brokers: the brokers that will be restarted :type brokers: map of broker ids and host names """ print("Will rest...
python
def register_for_deleted_resource(self, resource_id): """Registers for notification of a deleted resource. ``ResourceReceiver.deletedResources()`` is invoked when the specified resource is deleted or removed from this bin. arg: resource_id (osid.id.Id): the ``Id`` of the ``Resource`...
python
def temp(self, name, templates=None, n_indents=None, skipping=False): """ Get specific template of chosen programming language. Parameters ---------- :param param name : string The key name of the template. :param param templates : string, default: No...
java
public String getRawWMIObjectOutput(String wmiClass) throws WMIException { String rawData; try { if (this.properties != null || this.filters != null) { rawData = getWMIStub().queryObject(wmiClass, this.properties, this.filters, this.namespace, this.computerName); } else { rawData = getWMIStub()....
java
@Override public String getUserFacingMessage() { final StringBuilder bldr = new StringBuilder(); bldr.append("RESOLUTION FAILURE "); final String name = getName(); if (name != null) { bldr.append(" in "); bldr.append(name); } bldr.append("\n\t...
java
public static Compressor getCompressor(byte code) { Compressor compressor = TYPE_COMPRESSOR_MAP.get(code); if (compressor == null) { throw new SofaRpcRuntimeException("Compressor Not Found :\"" + code + "\"!"); } return compressor; }
java
private void quicksort(short[] a, int[] indexes, int left, int right) { if (right <= left) return; int i = partition(a, indexes, left, right); quicksort(a, indexes, left, i - 1); quicksort(a, indexes, i + 1, right); }
python
def release_singleton(self): '''deletes the data that lets our program know if it is running as singleton when calling check_if_open, i.e check_if_open will return fals after calling this ''' with suppress(KeyError): del self.cfg['is_programming_running_info'] ...
java
@Override protected void renderTagEnd() { try { if (StringUtils.isNotEmpty(this.output)) { this.output = toString(this.escape ? escape(this.output) : this.output); JspWriter writer = this.pageContext.getOut(); ...
java
private void delete(Node node) { if (handHot == node) { handHot = node.next; } if (handCold == node) { handCold = node.next; } if (handTest == node) { handTest = node.next; } node.remove(); }
java
@Override public IfixResourceWritable parseFileToResource(File assetFile, File metadataFile, String contentUrl) throws RepositoryException { ArtifactMetadata artifactMetadata = explodeArtifact(assetFile, metadataFile); // Throw an exception if there is no metadata and properties, we get the name a...
java
@Override public int doEndTag() throws JspException { if (!scopeSpecified) { pageContext.removeAttribute(var); } else { pageContext.removeAttribute(var, scope); } return EVAL_PAGE; }
python
def _time_to_expiry(expires): """ Determines the seconds until a HTTP header "Expires" timestamp :param expires: HTTP response "Expires" header :return: seconds until "Expires" time """ try: expires_dt = datetime.strptime(str(expires), '%a, %d %b %Y %H:%M:%S %...
java
public boolean doLocalCriteria(StringBuffer strFilter, boolean bIncludeFileName, Vector<BaseField> vParamList) { // Default BaseListener return super.doLocalCriteria(strFilter, bIncludeFileName, vParamList); // If can't handle remote }
python
def _batch_json_to_instances(self, json_dicts: List[JsonDict]) -> List[Instance]: """ Converts a list of JSON objects into a list of :class:`~allennlp.data.instance.Instance`s. By default, this expects that a "batch" consists of a list of JSON blobs which would individually be predicted ...
java
@Override public Collection<CRL> engineGetCRLs(CRLSelector selector) throws CertStoreException { if (selector == null) { Set<CRL> matches = new HashSet<>(); matchX509CRLs(new X509CRLSelector(), matches); matches.addAll(otherCRLs); return matches; ...
python
def recv_data(self): """ Grab the next frame and put it on the matrix. """ data, addr = self.sock.recvfrom(self.packetsize) matrix = map(ord, data.strip()) if len(matrix) == self.packetsize: self.matrix = matrix[:-4]
java
public void download(GenericUrl requestUrl, OutputStream outputStream) throws IOException { download(requestUrl, null, outputStream); }
python
def status(name, maximum=None, minimum=None, absolute=False, free=False): ''' Return the current disk usage stats for the named mount point name Disk mount or directory for which to check used space maximum The maximum disk utilization minimum The minimum disk utilization ...
java
public void marshall(RegisterPatchBaselineForPatchGroupRequest registerPatchBaselineForPatchGroupRequest, ProtocolMarshaller protocolMarshaller) { if (registerPatchBaselineForPatchGroupRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } tr...
python
def postcmd(self, stop: bool, line: str) -> bool: """Hook method executed just after a command dispatch is finished. :param stop: if True, the command has indicated the application should exit :param line: the command line text for this command :return: if this is True, the application ...
python
def _collapse_device(self, node, flat): """Collapse device hierarchy into a flat folder.""" items = [item for branch in node.branches for item in self._collapse_device(branch, flat) if item] show_all = not flat or self._quickmenu_actions == 'all...
python
def get_field_info(model): """ Given a model class, returns a `FieldInfo` instance, which is a `namedtuple`, containing metadata about the various field types on the model including information about their relationships. """ opts = model._meta.concrete_model._meta pk = _get_pk(opts) fie...
java
private Set<IGroupMember> toGroupMembers(List<String> groupNames, String fname) { final Set<IGroupMember> groups = new HashSet<>(); for (String groupName : groupNames) { // Assumes the groupName case matches the DB values. EntityIdentifier[] gs = GroupService....
python
def make_proxy_method(cls, name): """Creates a proxy function that can be used by Flasks routing. The proxy instantiates the Mocha subclass and calls the appropriate method. :param name: the name of the method to create a proxy for """ i = cls() view = getattr(i,...
java
public final BELScriptParser.set_statement_group_return set_statement_group() throws RecognitionException { BELScriptParser.set_statement_group_return retval = new BELScriptParser.set_statement_group_return(); retval.start = input.LT(1); Object root_0 = null; Token string_literal19=nul...
java
public Quaternionf rotateAxis(float angle, Vector3fc axis, Quaternionf dest) { return rotateAxis(angle, axis.x(), axis.y(), axis.z(), dest); }
java
public void setBucketLifeCycle(String bucketName, String lifeCycle) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException,InvalidArgume...
python
def stops_when(iterable, condition): # type: (Iterable, Union[Callable, Any]) -> Iterable """Stop yielding items when a condition arise. Args: iterable: the iterable to filter. condition: if the callable returns True once, stop yielding items. If it's not a callable, it w...
python
def __find_caller(stack_info=False): """ Find the stack frame of the caller so that we can note the source file name, line number and function name. """ frame = logging.currentframe() # On some versions of IronPython, currentframe() returns None if # IronPython is...
java
private SourceRefRange findSourceRefRange(List<Reference> refList, InputId inputId) { checkNotNull(inputId); // TODO(bashir): We can do binary search here, but since this is fast enough // right now, we just do a linear search for simplicity. int lastBefore = -1; int firstAfter = refList.size...
java
private static boolean setName(String ns, String name, Schema property) { boolean apply = false; final String cleanName = StringUtils.trimToNull(name); final String useName; if (!isEmpty(cleanName) && !cleanName.equals(((SchemaImpl) property).getName())) { useName = cleanName...
java
public CertificateDescriptionInner createOrUpdate(String resourceGroupName, String resourceName, String certificateName) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, resourceName, certificateName).toBlocking().single().body(); }
java
public static List<SecStrucInfo> getSecStrucInfo(Structure s) { List<SecStrucInfo> listSSI = new ArrayList<SecStrucInfo>(); GroupIterator iter = new GroupIterator(s); while (iter.hasNext()) { Group g = iter.next(); if (g.hasAminoAtoms()) { Object p = g.getProperty(Group.SEC_STRUC); if (!(p == null...
python
def write_external_data_tensors(model, filepath): # type: (ModelProto, Text) -> ModelProto """ Write external data of all tensors to files on disk. Note: This function also strips basepath information from all tensors' external_data fields. @params model: Model object which is the source of tenso...
python
def convert_to_row_table(self, add_units=True): ''' Converts the block into row titled elements. These elements are copied into the return table, which can be much longer than the original block. Args: add_units: Indicates if units should be appened to each row item. ...
python
def setup_interval_coinc_inj(workflow, hdfbank, full_data_trig_files, inj_trig_files, stat_files, background_file, veto_file, veto_name, out_dir, tags=None): """ This function sets up exact match coincidence and background estimation using a folded interval technique. """ if tags is N...
java
public long nextLong(long origin, long bound) { if (origin >= bound) throw new IllegalArgumentException(BAD_RANGE); return internalNextLong(origin, bound); }
python
async def _flush(self, request: 'Request', stacks: List[Stack]): """ Perform the actual sending to platform. This is separated from `flush()` since it needs to be inside a middleware call. """ for stack in stacks: await self.platform.send(request, stack)
java
@SuppressWarnings("unchecked") public <S, D> TypeMap<S, D> get(Class<S> sourceType, Class<D> destinationType, String typeMapName) { TypeMap<S, D> typeMap = (TypeMap<S, D>) typeMaps.get(TypePair.of(sourceType, destinationType, typeMapName)); if (typeMap != null) return typeMap; for (TypePair<?...
python
def load_tar_lzma_data(tlfile): """Load example sinogram data from a .tar.lzma file""" tmpname = extract_lzma(tlfile) # open tar file fields_real = [] fields_imag = [] phantom = [] parms = {} with tarfile.open(tmpname, "r") as t: members = t.getmembers() members.sort(ke...
java
public static boolean incrementColexicographically( LongTuple t, LongTuple min, LongTuple max, MutableLongTuple result) { Utils.checkForEqualSize(t, min); Utils.checkForEqualSize(t, max); Utils.checkForEqualSize(t, result); if (result != t) { resul...
python
def restart(self, subthread=None): """Restarts the loop function Tries to restart the loop thread using the current thread. Raises RuntimeError if a previous call to Loop.start was not made. :param subthread: True/False value used when calling Loop.start(subthread=subthread). If set to...
python
def program_rtr_all_nwk_next_hop(self, tenant_id, rout_id, next_hop, excl_list): """Program the next hop for all networks of a tenant. """ namespace = self.find_rtr_namespace(rout_id) if namespace is None: LOG.error("Unable to find namespace for r...
java
protected void addPartialInfo(ClassDoc cd, Content contentTree) { addPreQualifiedStrongClassLink(LinkInfoImpl.Kind.TREE, cd, contentTree); }
python
def _id(self): r""" The `SSHKey`'s ``id`` field, or if that is not defined, its ``fingerprint`` field. If neither field is defined, accessing this attribute raises a `TypeError`. """ if self.get("id") is not None: return self.id elif self.get("fingerp...
python
def load(self): """ Extract tabular data as |TableData| instances from an Excel file. |spreadsheet_load_desc| :return: Loaded |TableData| iterator. |TableData| created for each sheet in the workbook. |load_table_name_desc| ===============...
python
def _get_vispy_font_filename(face, bold, italic): """Fetch a remote vispy font""" name = face + '-' name += 'Regular' if not bold and not italic else '' name += 'Bold' if bold else '' name += 'Italic' if italic else '' name += '.ttf' return load_data_file('fonts/%s' % name)
java
@Override public StopFleetActionsResult stopFleetActions(StopFleetActionsRequest request) { request = beforeClientExecution(request); return executeStopFleetActions(request); }
java
public com.squareup.okhttp.Call getCharactersCharacterIdWalletJournalAsync(Integer characterId, String datasource, String ifNoneMatch, Integer page, String token, final ApiCallback<List<CharacterWalletJournalResponse>> callback) throws ApiException { com.squareup.okhttp.Call call = getC...
python
def remove(self, handler_id=None): """Remove a previously added handler and stop sending logs to its sink. Parameters ---------- handler_id : |int| or ``None`` The id of the sink to remove, as it was returned by the |add| method. If ``None``, all handlers are rem...